NestJS Http 模块

Sim*_*ann 1 javascript typescript axios nestjs

我从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');
  }
}
Run Code Online (Sandbox Code Playgroud)

如何从 Observable<AxiosResponse<Cat[]>> 中提取实际的猫数组?我尝试了以下操作,但它给了我一个订阅者对象,我也不知道如何解开该对象以获取实际数据。

const cats = await this.catsService.findAll().subscribe((val) => val);
Run Code Online (Sandbox Code Playgroud)

Isl*_*oud 8

使用.toPromise()已弃用,请检查:https://rxjs.dev/deprecations/to-promise

下面列出的是使用新方法的示例

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);


Run Code Online (Sandbox Code Playgroud)