【发布时间】:2022-08-01 21:13:57
【问题描述】:
一项服务正在获取 api 数据,每次 url 更改(路由器链接)时,我都需要在许多其他组件中保留并使用它,而无需再次调用 api。 Api 应该仅在服务运行时获取。
我需要让组件方法等到数据可用。
(为了便于阅读,实际代码减少到最低限度)
服务
constructor(private http: HttpClient) {
this.fetchData();
}
fetchData(): void {
this.http.get(this.endpointUrl).subscribe((res)=>{
this.data = res
});
}
getData(selectedCategory): DataType {
return this.data.find(cat => cat === selectedCategory)
}
零件
ngOnInit(): void {
this.activatedRoute.paramMap.subscribe(
(params: ParamMap) => {
// I need params before calling service method
// this method must wait until the \"data\" is available in service.
this.selectedCategory = this.service.getData(params.category);
}
);
}
标签: javascript angular rxjs