无法从 angular2 服务获取结果数组
Not able to fetch an array of results from angular2 service
这是我获取结果数组的服务代码:
getIndustries(): Observable<any> {
return this.http.get(`${IndustriesService.BASE_URI}/?searchTerm=`)
.map((res: Response) => res.json())
.catch((err: any) => Observable.throw('Server Error'));
}
下面是我的组件构造函数和与上面定义的服务通信的方法。
protected searchData: Array<Industry>;
constructor( private completerService: CompleterService,
private route: ActivatedRoute,
private industriesService: IndustriesService) {
this.fetchIndustryCodes();
}
private fetchIndustryCodes(): Subscription {
return this.route.params
.switchMap((industries: Industry[]) => this.industriesService.getIndustries())
.subscribe((industries_data: Industry[]) => {
this.searchData = industries_data
});
}
当我尝试在构造函数中打印此 searchData 时,它会打印一个 Subscription 对象。我不确定如何通过上述订阅获取数据。
关于这方面的任何指导都会有很大的帮助!
据我所知,您想在构造函数中使用 searchData
,但您不能这样做,因为异步调用需要时间并且构造函数中的代码在 fetchIndustryCodes()
完成之前执行。如果是这种情况,那你为什么不 subscribe
并在构造函数本身中等待呢?
constructor( private completerService: CompleterService,
private route: ActivatedRoute,
private industriesService: IndustriesService) {
this.fetchIndustryCodes().subscribe(
(industries_data) => {
this.searchData = industries_data;
// whatever you want to do here.
}, (err) => {console.log("error here")});
}
private fetchIndustryCodes(): Observable<type> {
return this._activatedRoute.params
.switchMap((industries) => this.industriesService.getIndustries())
.catch((err) => {console.log(err); return "service error";})
}
这是我获取结果数组的服务代码:
getIndustries(): Observable<any> {
return this.http.get(`${IndustriesService.BASE_URI}/?searchTerm=`)
.map((res: Response) => res.json())
.catch((err: any) => Observable.throw('Server Error'));
}
下面是我的组件构造函数和与上面定义的服务通信的方法。
protected searchData: Array<Industry>;
constructor( private completerService: CompleterService,
private route: ActivatedRoute,
private industriesService: IndustriesService) {
this.fetchIndustryCodes();
}
private fetchIndustryCodes(): Subscription {
return this.route.params
.switchMap((industries: Industry[]) => this.industriesService.getIndustries())
.subscribe((industries_data: Industry[]) => {
this.searchData = industries_data
});
}
当我尝试在构造函数中打印此 searchData 时,它会打印一个 Subscription 对象。我不确定如何通过上述订阅获取数据。
关于这方面的任何指导都会有很大的帮助!
据我所知,您想在构造函数中使用 searchData
,但您不能这样做,因为异步调用需要时间并且构造函数中的代码在 fetchIndustryCodes()
完成之前执行。如果是这种情况,那你为什么不 subscribe
并在构造函数本身中等待呢?
constructor( private completerService: CompleterService,
private route: ActivatedRoute,
private industriesService: IndustriesService) {
this.fetchIndustryCodes().subscribe(
(industries_data) => {
this.searchData = industries_data;
// whatever you want to do here.
}, (err) => {console.log("error here")});
}
private fetchIndustryCodes(): Observable<type> {
return this._activatedRoute.params
.switchMap((industries) => this.industriesService.getIndustries())
.catch((err) => {console.log(err); return "service error";})
}