Angular 两个异步对象,在调用时,一个还没加载好,报错。

需要通过要把Tour 的Line.name显示出来。
但是我直接用这个{{filterName(tour.line)}}提示
Cannot read property 'filter' of undefined。

也许是这里line还没获取到数据?
(ngif里加个&&line对象可以解决,感觉常规做法不是这样的吧)

export class Tour {
  id:number;
  line: number;
  description: string;
  person: string;
  length: number;
  date: string;
}

export class Line{
  id:number;
  name:string;
}

图片描述

阅读 3k
2 个回答

既然Cannot read property 'filter' of undefined那问题就出在this.lines.filter(...)linesundefined了。
那除非给lines附上初值为空数组(写在ngOnInit或者constructor里面),否则就只能加上 this.lines && this.lines.filter(...)咯。

const lname = this.lines ? this.lines.filter(line => line.id === lineID)[0].name : '加载中'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进