Angular 2 Http获取响应示例

时间:2016-10-23 17:15:22

标签: angular http typescript rxjs

从Angular 2中的http get获取json数据的正确方法是什么。我正在使用模拟端点测试一些本地数据,我可以在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()调用中看到我想要的数据但是在调用之后我似乎无法访问它...请告诉我我做错了什么!

3 个答案:

答案 0 :(得分:16)

这不应该以这种方式工作。当数据到达时,调用传递给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();
    });
}

答案 1 :(得分:5)

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

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

答案 2 :(得分:1)

这是一个易于使用的示例,允许您使用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();
    }
}