【发布时间】:2021-11-20 00:35:11
【问题描述】:
我试图了解如何从 Observable 类型的对象中提取数据,在没有进行一些研究之后,我主要依靠两种解决方案。订阅(在我的情况下不起作用或我使用不好),或不再存在的地图。我指定我使用嵌套。
这里我的目标是能够直接返回变量 this.followers 填充了答案的数据
这是我的代码。
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { GithubFollower } from './../../../../shared/github.models'
@Injectable()
export class GithubService {
private followers: GithubFollower[]
constructor(private httpService: HttpService) {}
getFollowers(id: string): GithubFollower[] {
this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`)
.subscribe(data => {
this.followers = data.data // this.followers = my data
console.log(this.followers); // print my data
});
console.log("here", this.followers); // print "here undefined"
return this.followers; // this.followers = []
}
}
如何从 Observable 中提取数据?
【问题讨论】:
-
为什么在您的情况下订阅不起作用?据我所知,地图运算符仍然存在。
-
这部分回答了它,但问题是我想等待我的请求返回然后能够返回这个的值
-
因为我使用了嵌套并且数据类型为
AxiosResponse<GithubFollower[], any> -
是的,但由于我使用的是 nestjs,
httpService对象来自@nestjs/axios库,顾名思义,它包含 axios 库的包装,因此变量类型为AxiosResponse<GithubFollower[], any>
标签: angular typescript rxjs nest