我有一个依赖于API响应的内容的组件。我已经设置了解析器,但是在我的数据准备好之前它仍然会返回。
如何使我的pull_categories()
函数等待接收到响应主体然后返回?而不是返回一个空对象,因为它不会等待,甚至在下面的情况下也不会调用它。
服务
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;
}
);
}
component.ts
categories = [];
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(
(data: Data) => {
this.categories = data.categories;
}
);
}
解析器
constructor(private categoriesService: CategoriesService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
return this.categoriesService.pull_categories();
}
app-routing.module.ts
{
path: '',
component: HomeComponent,
resolve: {categories: CategoriesResolverService}
}
首先,在service.ts中,您不需要订阅,您应该在要实际使用数据的位置进行订阅。subscribe
方法返回Subscription
,而不是http api的响应。
您可以将服务方法更新为
pull_categories(): Observable<any> {
return this.http.post('https://myapi.com/something', null);
}
pull_categories
Observable
当您在组件中(或任何地方)对其进行订阅时,方法将立即返回一个带有的方法,将执行http调用并在您的subscribe
部分中返回响应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句