从 NestJS 中的 AxiosResponse 获取对象键值对
Get object key-value pairs from AxiosResponse in NestJS
我正在开发一个用于学习目的的小型 NestJS 应用程序。
我按照文档的建议使用 @nestjs/axios
。我能够访问数据库(并执行所有 CRUD 操作)并使用以下解决方案将数据发送回客户端:
async getUser(username: string): Promise<Observable<AxiosResponse<{ _id: string; _rev: string; email: string; name: string }>>> {
return this.httpService.get(`${environment.cloudantBaseUrl}/users/${username}`).pipe(map((response) => response.data));
}
我需要从这个响应数据对象中获取电子邮件键值对,但是当我尝试访问它时,出现以下错误:
Property 'email' does not exist on type 'Observable<AxiosResponse<{ _id: string; _rev: string; email: string; name: string; }, any>>'.
我这样试过:
const user = await this.getUser(username);
console.log(user.email);
当我将用户常量记录到控制台时,我得到了这个签名:
Observable {
source: Observable { _subscribe: [Function (anonymous)] },
operator: [Function (anonymous)]
}
所以我的问题是:如何从 AxiosResponse 对象中提取某些键值对?
提前致谢!
几件事:
直接使用 Observable 时不需要使用 async/await
。如果你想要 async/await
,你需要将 Observable 包装在 lastValueFrom()
中以使其成为一个承诺。如果您不使用 lastValueFrom
,则可以在方法声明中删除 async
,在 return 类型
中删除 Promise<>
由于您已经在映射响应,因此不应使用 AxiosResponse<>
。只要做 Observable<{ _id: string; _rev: string; email: string; name: string }>
要在后面的函数中使用 Observable,你只需要继续使用 .pipe()
和 rxjs 运算符,如 map
、switchMap
和 tap
。 learnrxjs.io 是了解这些运算符可以做什么的好资源。
- 当您想要记录可观察值的值时,可以使用
tap
运算符。 .pipe(tap(console.log))
是它的快速绑定
我正在开发一个用于学习目的的小型 NestJS 应用程序。
我按照文档的建议使用 @nestjs/axios
。我能够访问数据库(并执行所有 CRUD 操作)并使用以下解决方案将数据发送回客户端:
async getUser(username: string): Promise<Observable<AxiosResponse<{ _id: string; _rev: string; email: string; name: string }>>> {
return this.httpService.get(`${environment.cloudantBaseUrl}/users/${username}`).pipe(map((response) => response.data));
}
我需要从这个响应数据对象中获取电子邮件键值对,但是当我尝试访问它时,出现以下错误:
Property 'email' does not exist on type 'Observable<AxiosResponse<{ _id: string; _rev: string; email: string; name: string; }, any>>'.
我这样试过:
const user = await this.getUser(username);
console.log(user.email);
当我将用户常量记录到控制台时,我得到了这个签名:
Observable {
source: Observable { _subscribe: [Function (anonymous)] },
operator: [Function (anonymous)]
}
所以我的问题是:如何从 AxiosResponse 对象中提取某些键值对?
提前致谢!
几件事:
直接使用 Observable 时不需要使用
中删除async/await
。如果你想要async/await
,你需要将 Observable 包装在lastValueFrom()
中以使其成为一个承诺。如果您不使用lastValueFrom
,则可以在方法声明中删除async
,在 return 类型Promise<>
由于您已经在映射响应,因此不应使用
AxiosResponse<>
。只要做Observable<{ _id: string; _rev: string; email: string; name: string }>
要在后面的函数中使用 Observable,你只需要继续使用
.pipe()
和 rxjs 运算符,如map
、switchMap
和tap
。 learnrxjs.io 是了解这些运算符可以做什么的好资源。- 当您想要记录可观察值的值时,可以使用
tap
运算符。.pipe(tap(console.log))
是它的快速绑定
- 当您想要记录可观察值的值时,可以使用