繁体   English   中英

Angular 2 Http获取响应示例

[英]Angular 2 Http Get Response Example

在Angular 2中从http获取json数据的正确方法是什么。我正在使用http.get()端点测试一些本地数据,我可以在http.get()看到结果,但我不能在本地分配它或有一些时间问题。 这是我的简单服务:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';  // we need to import this now

    @Injectable()
    export class MyHttpService {
    constructor(private _http:Http) {}

    getDataObservable(url:string) {
        return this._http.get(url)
            .map(data => {
                data.json();
                console.log("I CAN SEE DATA HERE: ", data.json());
        });
    }
}

以下是我试图分配数据的方式:

import {Component, ViewChild} from "@angular/core";

import { MyHttpService } from '../../services/http.service';

@Component({
    selector: "app",
    template: require<any>("./app.component.html"),
    styles: [
        require<any>("./app.component.less")
    ],
    providers: []
})
export class AppComponent implements OnInit, AfterViewInit {
    private dataUrl = 'http://localhost:3000/testData';  // URL to web api
    testResponse: any;

    constructor(private myHttp: MyHttpService) {
    }

    ngOnInit() {
        this.myHttp.getDataObservable(this.dataUrl).subscribe(
            data => this.testResponse = data
        );
        console.log("I CANT SEE DATA HERE: ", this.testResponse);
    }
}

我可以在get()调用中看到我想要的数据但是在调用之后我似乎无法访问它...请告诉我我做错了什么!

这不应该以这种方式工作。 当数据到达时,调用传递给observable的回调。 需要访问此数据的代码必须位于回调内。

ngOnInit() {
    this.myHttp.getDataObservable(this.dataUrl).subscribe(
        data => {
          this.testResponse = data;
          console.log("I CANT SEE DATA HERE: ", this.testResponse);
        }
    );
}

更新

getDataObservable(url:string) {
    return this._http.get(url)
        .map(data => {
            data.json();
            // the console.log(...) line prevents your code from working 
            // either remove it or add the line below (return ...)
            console.log("I CAN SEE DATA HERE: ", data.json());
            return data.json();
    });
}

因为http调用是异步的。 您需要在订阅功能中进行分配。 试试这样:

this.myHttp.getDataObservable(this.dataUrl).subscribe(
            data => {
                      this.testResponse = data ;
                      console.log("I SEE DATA HERE: ", this.testResponse);
                     }
        );

这是一个易于使用的示例,允许您使用promises。

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Config } from '../Config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class Request {

    constructor(public http: Http)
    {

    }

    get(url): Promise<any>
    {
        return this.http.get(Config.baseUrl + url).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }

    post(url, data): Promise<any>
    {
        return this.http.post(Config.baseUrl + url, data).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM