【问题标题】:How to use observable data from an external api in nestjs?如何在nestjs中使用来自外部api的可观察数据?
【发布时间】:2022-01-02 02:24:03
【问题描述】:

我正在尝试在带有 axios 的 Nestjs 中使用外部 api。

@Injectable()
export class PIntegration {
  constructor(private httpService: HttpService) { }
  API = process.env.API || 'http://localhost:3000';
  header = { headers: { 'Content-Type': 'application/json' } };

  async getPrestacionById(id: string): Promise<Observable<IPrestacion>>{
   
    return this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data));
  }
}

我的服务类如下所示:

@Injectable()
export class ProductService{
    constructor(private pIntegration: PIntegration){}
    async producto(id: string) {
        const infoPrestacion = await  this.pIntegration.getPrestacionById(id);
        console.log({ infoPrestacion })
        if (infoPrestacion)
        {
             if (infoPrestacion.detalles) {
                console.log(infoPrestacion.detalles)
                console.log("tiene detalles")
            }
        }
        return infoPrestacion;
    }
}

但是,如果我 console.log 值“infoPresacion”,结果如下:

{
  infoPrestacion: Observable {
    source: Observable { _subscribe: [Function (anonymous)] },
    operator: [Function (anonymous)]
  }
}

它没有达到第二个,因为它还没有解决。是否可以等待结果解决(我没有 HttpModule 的任何配置)?返回实际上获取对象本身“infoPresacion”,但我需要使用这些值而不是返回该对象。

【问题讨论】:

  • 看来你不想使用 rxjs obervables,那就关注这个indepth.dev/posts/1287/…
  • @MicaelLevi 我正在寻找这两种方法,但我用“lastValueFrom”解决了这个问题(看不到该网站,服务器似乎已关闭)

标签: axios nestjs nestjs-config


【解决方案1】:

我用这个解决了我的问题,我希望这能满足你的需要。

如果您将 observable 作为一个承诺,那么有两种解决方案可能适合您。

在您使用外部 api 的课程中​​:

添加 lastValueFrom,它通过订阅 observable、等待它完成并使用观察到的流中的最后一个值解析返回的 promise 来将 observable 转换为 Promise。

firstValueFrom 也可以是一个解决方案,它与 lastValuefrom 在你的承诺得到解决时获取第一个元素相反。

@Injectable()

export class PIntegration {
  constructor(private httpService: HttpService) { }
  API = process.env.API || 'http://localhost:3000';
  header = { headers: { 'Content-Type': 'application/json' } };

  async getPrestacionById(id: string): Promise<IPrestacion>{
   
    return lastValueFrom(this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data)));
  }
}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2018-06-23
    • 2022-12-11
    相关资源
    最近更新 更多