我正在尝试使用 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());
}
}
我无法获取数据,当我尝试使用它进行测试时console.log('response ' + this.jsonData);
在上面的 getData() 方法中,我得到response undefined
在浏览器中。
PS:jsonData是客户端组件类的字符串属性。