我曾尝试在Google上进行搜索,但找不到解决方案,所以这是问题所在:
我正在尝试使用http
模块以角度方式从服务器加载数据,但问题是多个组件都需要特定数据,这是我到目前为止尝试过的:
@Injectable()
export class CoreService {
data: any = null;
Event: Observable<Object>;
isLoadingData: boolean = false;
constructor(private httpService: HttpService) {
if(!isNull(this.data)) { return observer.next({data:this.data, isBusy: isLoading}) } // If Data is not null then return the data
if(this.isLoadingBaseDirectory) {
return observer.next({data:this.isLoadingBaseDirectory, isBusy: this.isLoading}) // if http call is busy loading the data then return isBusy true
}
this.isLoading = true; // Data is empty and we are not loading data, then set isLoading flag to true
this.httpService.get(`coreEnv/getPodiumBaseDirectory`).map((res:Response) => { return res.json() }).subscribe((data) => {
this.data = data; // data load complete
this.isLoading = false;
observer.next({data:this.data, isBusy: this.isLoading});
})
}
}
// Component ngOnInit Method:
this.isBusy = true; // Component Loading Flag
this.coreService.baseDirectoryEvent.subscribe((data) => {
if(!data['isBusy']) {
this.data = data['data'];
this.isBusy = false;
}
})
现在,如果我在多个组件中使用上述代码并将它们都加载到同一页面中,那么第二个组件确实会从服务获取响应
isBusy
标志true
,因为第一个组件尝试加载设置了isBusy
标志的数据到服务中的true
,但是当服务成功从服务器加载数据时,它不会触发第二个组件的最后一个observer.next
,而是第一个组件获取数据。 最佳答案
正如@GünterZöchbauer在他的评论中提到的,要实现此功能,请参见答案:What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?
为我工作!
关于javascript - 从服务器加载数据时的Angular Service监听,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43896778/