我尝试在谷歌上搜索但找不到解决方案,所以问题是:
我正在尝试使用 http
从服务器加载数据 Angular 模块,但问题是多个组件需要特定数据,这是我迄今为止尝试过的:
@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
对于第二个组件,但第一个组件获取数据。
最佳答案
你使用路由吗?如果是这样,您可以使用解析器定义无组件父路由。解析器可以获取数据,然后所有子级都可以访问该数据。
我这里有一个例子:https://github.com/DeborahK/Angular-Routing在 APM-Final
文件夹中。查看product-resolver.service.ts。
作为该父路由的子路由的任何路由都可以使用类似于以下的语法访问数据:
ngOnInit(): void {
this.route.parent.data.subscribe(data => {
this.product = data['product'];
});
}
这是在数据属性上使用订阅,因为在我的示例中,可以使用不同的参数重新检索数据。
关于javascript - 从服务器加载数据时,Angular 服务监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896778/