【问题标题】:How to extract data from an Observable如何从 Observable 中提取数据
【发布时间】: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&lt;GithubFollower[], any&gt;
  • 是的,但由于我使用的是 nestjs,httpService 对象来自 @nestjs/axios 库,顾名思义,它包含 axios 库的包装,因此变量类型为 AxiosResponse&lt;GithubFollower[], any&gt;

标签: angular typescript rxjs nest


【解决方案1】:

虽然.toPromise 在 RxJs 8 中已被弃用,但您可以在 rxjs 版本 7 及以下版本中使用它。所以试试这个:

async getFollowers(id: string): GithubFollower[] {
    const githubData = await this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`).toPromise()
    this.followers = githubData.data
    return this.followers; // this.followers now returns the followers instead of undefined
  }

【讨论】:

    【解决方案2】:

    根据我昨天晚上的问题,我找到了两个解决方案。 第一个是使用pipe 函数(即使我不太了解它的作用,我很乐意在这篇文章的 cmets 中进行解释),它为我们提供了以下信息:

      getFollowers(id: string): Observable<DashBoardResponse> {
        return this.httpService
          .get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`)
          .pipe(
            map(res => {
              const response: DashBoardResponse = {
                code: res.data !== [] ? 200 : 400,
                message: res.data !== [] ? 'success' : 'Possible bad id',
                response: res.data
              }
              return response;
            })
          )
      }
    

    nest 能够在将响应发送回客户端之前从控制器中提取响应。

    我可以拥有的第二个解决方案是对@KZoeps 进行了一些修改,因为在当前版本的嵌套中,如果不返回Promise,就不可能使用async/await 函数。 这是代码: 这里我的目标是能够直接返回变量this.followers填充了答案的数据

      async getFollowers(id: string): Promise<DashBoardResponse> {
        this.followers = await (await this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`).toPromise()).data
        return new Promise((resolve, reject: (reason?: DashBoardResponse) => void) => {
          if (this.followers !== []) {
            resolve({
              code: 200,
              message: 'success',
              response: this.followers
            });
          } else {
            reject({
              code: 400,
              message: 'Possible bad id',
              response: []
            })
          }
        })
      }
    

    无论如何感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 2018-10-12
      相关资源
      最近更新 更多