【问题标题】:NestJS Http ModuleNestJS Http 模块
【发布时间】:2021-08-31 07:01:28
【问题描述】:

我从 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');
  }
}

如何从 Observable> 中提取实际的猫数组? 我尝试了以下方法,但它给了我一个订阅者对象,我也不知道如何打开它来获取实际数据。

const cats = await this.catsService.findAll().subscribe((val) => val);

【问题讨论】:

  • 试试await this.catsService.findAll().toPromise();

标签: javascript typescript axios nestjs


【解决方案1】:

试试这个:

  findAll(): Observable<Cat[]> {
    return this.httpService.get('http://localhost:3000/cats')
      .pipe(map(response => response.data);
  }

【讨论】:

    【解决方案2】:
    @Injectable()
    export class CatsService {
      constructor(private httpService: HttpService) {}
    
      findAll(): Promise<Cat[]> {
        return this.httpService.get('http://localhost:3000/cats').toPromise();
      }
    

    }

    const cats = await this.catsService.findAll().data
    

    为我工作。

    【讨论】:

    【解决方案3】:

    现在不推荐使用.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);
    
    
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2021-08-12
      • 2021-11-06
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多