简体   繁体   English

Angular 2 Http获取响应示例

[英]Angular 2 Http Get Response Example

What is the correct way to get json data from an http get in Angular 2. I am working on testing some local data with a mocked endpoint, and I can see the result in the http.get() but I cannot assign it locally or there is some timing issue. 在Angular 2中从http获取json数据的正确方法是什么。我正在使用http.get()端点测试一些本地数据,我可以在http.get()看到结果,但我不能在本地分配它或有一些时间问题。 Here is my simple service: 这是我的简单服务:

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());
        });
    }
}

And here is how i'm trying to assign the data: 以下是我试图分配数据的方式:

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);
    }
}

I can see the data I want in the get() call but I don't seem to have access to it after that call...please tell me what i'm doing wrong! 我可以在get()调用中看到我想要的数据但是在调用之后我似乎无法访问它...请告诉我我做错了什么!

That's not supposed to work this way. 这不应该以这种方式工作。 When the data arrives the callback passed to the observable is called. 当数据到达时,调用传递给observable的回调。 Code that needs to access this data has to be inside the callback. 需要访问此数据的代码必须位于回调内。

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

update 更新

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();
    });
}

Because http call is async. 因为http调用是异步的。 You need to make assignments in the subscribe function. 您需要在订阅功能中进行分配。 Try like this: 试试这样:

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

Here is an easy to use sample that allows you to use promises. 这是一个易于使用的示例,允许您使用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