使用Angular 2 Http从REST Web服务获取数据

问题描述 投票:2回答:1

我正在尝试使用Angular 2 Http从REST Web服务获取数据。

我首先在调用它的客户端组件类的构造函数中注入服务:

constructor (private _myService: MyService,
             private route: ActivatedRoute,
             private router: Router) {}

我添加了一个getData()方法,该方法调用MyService方法从Web服务获取数据:

getData(myArg: string) {
    this._myService.fetchData(myArg)
      .subscribe(data => this.jsonData = JSON.stringify(data),
        error => alert(error),
        () => console.log("Finished")
      );

    console.log('response ' + this.jsonData);

我在客户端组件类的ngOnInit方法中调用了getData()方法(我正确地导入并实现了OnInit接口):

this.getData(this.myArg);

这是MyService服务:

import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import 'rxjs/add/operator/map';

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

        fetchData(myArg: string) {
            return this._http.get("http://date.jsontest.com/").map(res => res.json());
        }
    }

我无法获取数据,当我尝试在上面的getData()方法中使用console.log('response ' + this.jsonData);进行测试时,我在浏览器中获得了response undefined

PS:jsonData是客户端组件类的字符串属性。

javascript rest http typescript angular
1个回答
2
投票

由于http请求是异步的,因此在您尝试将其记录到控制台时不会设置this.jsonData。而是将该日志放入订阅回调中:

getData(myArg: string){     
    this._myService.fetchData(myArg)
             .subscribe(data => { 
                            this.jsonData = JSON.stringify(data)
                            console.log(this.jsonData);
                        },
                        error => alert(error),
                        () => console.log("Finished")
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.