我有一个组件依赖于其内容的 API 响应。我已经设置了解析器,但它仍然会在我的数据准备好之前返回。
如何让我的pull_categories()
函数等到收到响应正文然后返回?而不是返回一个空对象,因为它不会等待甚至在我下面的例子中调用它。
服务.ts
private _categories = [];
constructor(private http: HttpClient) { }
pull_categories() {
this.http.post('https://myapi.com/something', null)
.subscribe(
data => {
this._categories = data['response'];
return this._categories;
}
);
}
组件.ts
categories = [];
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(
(data: Data) => {
this.categories = data.categories;
}
);
}
解析器.ts
constructor(private categoriesService: CategoriesService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
return this.categoriesService.pull_categories();
}
应用程序路由.module.ts
{
path: '',
component: HomeComponent,
resolve: {categories: CategoriesResolverService}
}