Angular 2 Http获取响应示例

DHW*_*DHW 17 http rxjs typescript angular

在Angular 2中从http获取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());
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 18

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

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

更新

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();
    });
}
Run Code Online (Sandbox Code Playgroud)


Sef*_*efa 5

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

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