【问题标题】:Angular 6, RxJS return undefined objectAngular 6,RxJS 返回未定义的对象
【发布时间】:2018-06-12 16:19:45
【问题描述】:

我的地图/过滤器函数没有返回我从内存服务接收到的对象。

this.myService.getEventMedia().subscribe(
  (response) => {
    return response.map((res) => {
      this.returnObj = res.dataObj.filter((data) => {
       if(data.id === id) {
         console.log('event is ', data)
         return data;
       }

      })
    })
  }
);

在此响应和/或 ngAfterViewInit() returnObj 之后是未定义的控制台日志记录。我的过滤器函数中的数据具有价值,我可以控制台记录 data.id

我的模型如下所示

export interface Model {
  id: number;
  name: string;
  data: Data[];
}

【问题讨论】:

  • 你不应该从 subscribe 块返回一些东西。你想完成什么?
  • 我想将匹配的数据分配给returnObj,我还是rxjs的新手,所以还在学习
  • @Generaldeep 你能显示response的json吗?
  • @CozyAzure,响应是一个包含 2 个数组的对象,其中包含多个对象。由于隐私问题,我无法分享 json 响应。
  • filtermap 不是一个好主意,虽然

标签: angular rxjs observable rxjs6


【解决方案1】:

也许将您的服务订阅更改为此?

this.myService.getEventMedia().subscribe(
  (response) => {
    this.returnObject = response.map((res) => {
      return res.dataObj.filter((data) => {
       if(data.id === id) {
         console.log('event is ', data)
         return data;
       }
      })
    })
  }
);

这样,您的返回对象就会被设置到地图上。现在返回你的地图对你没有任何帮助。

【讨论】:

    【解决方案2】:

    您不应从传递给subscribe 的回调方法返回值,因为它们在方法签名中都是无效的。

    如果您想要以某种方式转换服务的响应,然后将转换后的值分配给 returnObj 类成员,那么您应该执行以下操作:

    this.myService.getEventMedia()
      .pipe(
          map(response => this.transformResponse(response))
       )
      .subscribe(mappedResponse => this.returnObj = mappedResponse);
    
    private transformResponse(response:Object): Object {
       // your transformation logic goes here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 2019-01-05
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多