【发布时间】:2016-11-08 16:14:55
【问题描述】:
我正在尝试使用 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