【问题标题】:How to use map inside subscribe rxjs6如何在订阅 rxjs 6 中使用地图
【发布时间】:2018-09-04 18:10:48
【问题描述】:

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

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

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

错误:“Modelclass”类型上不存在属性“map”。

服务响应

[
  {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 }));
}

【问题讨论】:

  • 您已在订阅中使用map。你有什么问题?
  • @but which is not working getting below Error: Property 'map' does not exist on type 'Modelclass'.' but which is working in below code this.dataService.fetchData().subscribe(this.fetchResponse); private fetchResponse(response): void =&gt; { [...this.DataMappingField ]= response.map(({ ID: id, Name: name }) =&gt; ({ id, name })); } .. so which is not working in订阅
  • 你试过了吗...... .subscribe((response: any) => { // 这里是你的代码 //});

标签: rxjs angular6 rxjs6


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2018-11-09
    相关资源
    最近更新 更多