Http 使用Angular 2中服务的Json文件
我有服务。 在构造函数中:Http 使用Angular 2中服务的Json文件,http,typescript,angular,observable,Http,Typescript,Angular,Observable,我有服务。 在构造函数中: export class Service { _data: any constructor(private http: Http) { this.http .get('../assets/my_json_file.json') .map(x => x.json() ) .subscribe( (data) => this._data = data ) consol
export class Service {
_data: any
constructor(private http: Http) {
this.http
.get('../assets/my_json_file.json')
.map(x => x.json() )
.subscribe( (data) =>
this._data = data
)
console.log(this._data)
}
console.log
返回undefined
,尽管如果console.log
被移动到传递给subscribe
的函数中,它会显示数据
我的目标是在服务中有许多函数getStuff()
看到但没有帮助找出错误所在此.http.get('../assets/my_json_file.json')
是异步的,这意味着对服务器的调用将在稍后执行,当服务器的响应最终到达时,传递给.subscribe(…)
的回调将随响应一起调用。“计划”是指在完成先前计划的任务后,将任务添加到事件队列中,以便稍后执行
在调度http.get(…)
调用后,将执行console.log(此.\u数据)
。这甚至是在对服务器的调用启动之前
http.get(…)
调用也仅在订阅了http.get(…)
返回的可观察对象时安排,因为可观察对象是惰性的
使用map(…)
而不是subscribe(…)
返回一个可观察的
而不是订阅
,它允许服务用户将自己的代码链接到响应事件
@Injectable()
export class Service {
_data: any
constructor(private http: Http) {}
getData() {
this.http
.get('../assets/my_json_file.json')
.map(x => x.json() )
.map( (data) =>
this._data = data
)
console.log(this._data)
}
}
在组件中,您可以像这样使用它
export class MyComponent {
constructor(service:Service) {
// `subscribe` actually initiates the call to the server
service.getData().subscribe(result => console.log(result));
}
}
另见
这样,您就可以在实例化服务时启动对服务器的调用,而不仅仅是在使用该服务的组件订阅之后。您不能这样使用它。http是异步的,您希望使用它进行同步。您可以在服务中使用getStuff函数,但需要在数据准备就绪时开始调用这些函数,这只能通过在应用程序组件中使用另一个订户来实现。因此,json并不重要,数据是通过与服务器相同的http获取的。