首页 > 解决方案 > 如何从 observable 中获取正确的数据

问题描述

我正在尝试从可观察到的数据中获取数据,但我没有得到正确的数据。这是我对我的 API 的调用

    getLastxScans(amount: number): Observable<Scan[]> {
    return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amount}`);
  }

当我订阅它时它会返回这个

{scans: Array(30)}

当我尝试用此数据填充 Scan[] 时,它不起作用。我是否需要更深入地了解对象以提取数据?如果是这样,我该怎么做?我试过这样做

    this.deviceService.getLastxScans(this.scanAmount)
      .subscribe(scans => this.scans = scans);

而这种方式

this.deviceService.getLastxScans(this.scanAmount)
    .subscribe(res => this.scans = res.scans);

标签: angulartypescriptrxjsobservable

解决方案


使用:(因为数组是scans响应的key的值)

this.deviceService.getLastxScans(this.scanAmount)
    .subscribe(res => this.scans = res.scans);

从评论中,您还可以执行以下操作:

getLastxScans(amount: number): Observable<Scan[]> {
   return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amount}`)
              .pipe(
                 map((res:any) => res.scans)
              );
}

推荐阅读