【问题标题】:Angular 2 Http Get Response ExampleAngular 2 Http 获取响应示例
【发布时间】:2017-03-05 11:24:35
【问题描述】:

在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() 调用中看到我想要的数据,但在那次调用之后我似乎无法访问它...请告诉我我做错了什么!

【问题讨论】:

  • 这就是订阅回调的重点。

标签: angular http typescript rxjs


【解决方案1】:

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

【讨论】:

  • 好的,感谢您的解释,我对 Angular 还是新手以及如何正确实现 http 调用。话虽如此,如果我像上面显示的那样处理回调中的数据,我仍然看到:
  • I CANT SEE DATA HERE: undefined
  • map(...)´ function needs to return the value, otherwise the subscriber won't get anything. If 你删除了console.log... 行,data.json() 应该隐式返回结果。
  • 感谢您进一步解释,从服务中删除日志调用解决了您所说的问题。我不知道电话会对响应产生这种影响,但现在它是有道理的。再次感谢....我知道我还有很多东西要学。
  • 是的,如果没有显式返回,最后一个表达式的结果会从函数中隐式返回。 console.log() 不返回任何内容,这就是你得到undefined 的原因。
【解决方案2】:

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

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

【讨论】:

  • 如何在.html页面中使用this.testResponse? {{testResponse }} 这个显示为空对象。
【解决方案3】:

这是一个易于使用的示例,可让您使用 Promise。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多