如何从请求中返回 HttpClient 响应正文? [英] How to return HttpClient response body from a request?

查看:38
本文介绍了如何从请求中返回 HttpClient 响应正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,它的内容依赖于 API 响应.我已经设置了解析器,但它仍然在我的数据准备好之前返回.

I have a component that relies on an API response for its content. I have set up the resolver but it still returns before my data is ready.

如何让我的 pull_categories() 函数等到收到响应正文然后返回?而不是返回一个空对象,因为它不会等待甚至在我下面的例子中调用它.

How can I make my pull_categories() function wait until the response body is received and then return? Rather than returning an empty object because it won't wait or even call it in my case below.

service.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;
        }
    );
}

<小时>

component.ts


component.ts

categories = [];

constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.route.data.subscribe(
        (data: Data) => {
            this.categories = data.categories;
        }
    );
}

<小时>

解析器.ts


resolver.ts

constructor(private categoriesService: CategoriesService) { }

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return this.categoriesService.pull_categories();
}

<小时>

app-routing.module.ts


app-routing.module.ts

{
    path: '',
    component: HomeComponent,
    resolve: {categories: CategoriesResolverService}
}

推荐答案

首先,在 service.ts 中你不需要订阅,你应该在你想要实际消费数据的地方订阅.subscribe 方法返回 Subscription,而不是来自 http api 的响应.

First thing, in service.ts you don't need to subscribe, You should subscribe where you want to actually consume the data. subscribe method returns Subscription, not the response from the http api.

您可以将您的服务方法更新为

You can update your service method as

pull_categories(): Observable<any> {
    return this.http.post('https://myapi.com/something', null);
}

pull_categories 方法将立即返回一个 Observable,当您在组件(或任何地方)订阅它时,将执行 http 调用并返回响应您的 订阅 部分.

pull_categories method will return immediately with an Observable, when you subscribe on it in your component (or anywhere), http call will be executed and response will be returned in your subscribe section.

这篇关于如何从请求中返回 HttpClient 响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆