首页 文章

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

提问于
浏览
2

我正在尝试使用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是客户端组件类的字符串属性 .

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

相关问题