首页 > 解决方案 > 如何在订阅 rxjs6 中使用地图

问题描述

我有一个返回 Observable 的服务,在得到响应后我映射响应并将结果分配给数组。

  this.dataService.fetchData().subscribe(response =>{
    [...this.DataMappingField ]=  response.map(({ ID: id, Name: name }) => ({ id, name }));
  });

在订阅中使用传播运算符时,我收到以下错误。

错误:“模型类”类型上不存在属性“地图”。

服务响应

[
  {ID: 6197, Name: 'A', desc: null,catergory:'lap'},
  {ID: 6198, Name: 'B', desc: null,catergory:'lap'}
]

在服务中,fetchData方法:

fetchData(): Observable<Modelclass> {
  return this.http
    .get<Modelclass>(REQUEST_URL)
    .pipe(
      tap(response => response)
    );
}

型号类:

export class Modelclass {
  ID: any;
  Name: string;
}

但是以下代码在使用方法调用时工作正常:

this.dataService.fetchData().subscribe(this.fetchResponse);

private fetchResponse(response): void => {
  [...this.DataMappingField ]= response.map(({ ID: id, Name: name }) => ({ id, name }));
}

标签: rxjsangular6rxjs6

解决方案


我认为问题是不正确的响应输入。方法的定义fetchData应该是这样的:

fetchData(): Observable<Modelclass[]> {
  return this.http
    .get<Modelclass[]>(REQUEST_URL)
    .pipe(
      tap(response => response)
    );
}

注意我Modelclass[]用作响应类型。


推荐阅读