【问题标题】:How can I map through objects in angular with subscribe method?如何使用 subscribe 方法以角度映射对象?
【发布时间】:2021-08-28 02:05:38
【问题描述】:

我从 nodejs 后端获取位置作为对象数组。我已经在前端以角度订阅了它,它正在返回对象数组。如何获取每个对象的 name 属性?我正在尝试使用角度自动完成功能进行自动过滤。

组件文件

getLocations(){
    this.locationService.getLocations().subscribe( (res )=> {
      console.log(res);
    })
  }

服务文件


  getLocations(): Observable<LocationTypes>  {
    const makeReqURL = `${this.apiURL}/`;
    const getLocations = this.http.get<LocationTypes>(makeReqURL, { })
    return getLocations;
  }

来自前端响应的控制台日志图像。

添加 PIPE 后出错

提前谢谢你。

未定义的屏幕截图

错误信息

【问题讨论】:

  • 你的意思是使用getLocations.pipe(map(lt =&gt; lt.name)).subscribe(name =&gt; console.log(name))
  • @Pieterjan 我试过这个并且它返回 undefined onthe conslose。

标签: javascript node.js angular mongodb frontend


【解决方案1】:

解决方案:使用管道然后点击从响应中获取名称。

import { tap } from 'rxjs/operators';

getLocations() {
    this.locationService
    .getLocations()
    .pipe(tap((response: any) => {
        response.map((data: any) => {
            return console.log(data.name);
        })
    }))
    .subscribe();

}

【讨论】:

  • 我试过这个,它有一个编译错误。我将在错误消息的问题中添加图像。
  • @Dave 你必须像这样导入“tap”运算符: import { tap } from 'rxjs/operators' 在我们的 ts 文件顶部
  • 谢谢,我试过了,当我执行“res.name”时,控制台中仍然出现“未定义”。但是,当我只记录“res”时,它会包含完整的 ogbects 数组。我对钓鱼者还是很陌生,我不确定我在这里做错了什么。
  • 你能上传你的回复屏幕吗?
  • @I3artosh 我上传了一张图片。
猜你喜欢
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 2016-05-05
相关资源
最近更新 更多