[英]NestJS Http Module
I took this example from the nestJS docs ( https://docs.nestjs.com/techniques/http-module#http-module ), which is a minimal example of my problem:我从nestJS文档( https://docs.nestjs.com/techniques/http-module#http-module )中获取了这个例子,这是我的问题的一个最小例子:
@Injectable()
export class CatsService {
constructor(private httpService: HttpService) {}
findAll(): Observable<AxiosResponse<Cat[]>> {
return this.httpService.get('http://localhost:3000/cats');
}
}
How can I extract the actual Array of Cats from the Observable<AxiosResponse<Cat[]>>?如何从 Observable<AxiosResponse<Cat[]>> 中提取实际的猫数组? I tried the following but it gives me a subscriper object which I also don't know how to unwrap to get the actual data.
我尝试了以下方法,但它给了我一个订阅者 object,我也不知道如何打开它来获取实际数据。
const cats = await this.catsService.findAll().subscribe((val) => val);
Try this:尝试这个:
findAll(): Observable<Cat[]> {
return this.httpService.get('http://localhost:3000/cats')
.pipe(map(response => response.data);
}
@Injectable()
export class CatsService {
constructor(private httpService: HttpService) {}
findAll(): Promise<Cat[]> {
return this.httpService.get('http://localhost:3000/cats').toPromise();
}
} }
const cats = await this.catsService.findAll().data
worked for me.为我工作。
Using .toPromise()
is deprecated now check this: https://rxjs.dev/deprecations/to-promise现在不推荐使用
.toPromise()
进行检查: https://rxjs.dev/deprecations/to-promise
Listing below is an example using the new approach下面的清单是使用新方法的示例
UPDATE Oct 2021 2021 年 10 月更新
import { lastValueFrom } from 'rxjs';
.
.
.
const observable = await this.httpService.get('url').pipe(map((res) => res.data));
// you can use the data object now !!
const data = await lastValueFrom(observable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.