角度TS遍历传入数据

时间:2019-01-23 13:06:57

标签: angular typescript loops

我试图遍历输入数据数组,以便可以在传单中的地图上显示信息!

这是我的课:

export class OpenStreetMapComponent implements OnInit {
  @Output() private add = new EventEmitter();
  @Output() private edit = new EventEmitter<number>();
  artworkList: Artwork[];

传入的数据存储在ArtworkList数组中

constructor(private artworkService: ArtworkService) { }
  ngOnInit() {
    this.refresh();
  }

  refresh() {
    this.artworkService.retrieveAll().then(
      artworkList => this.artworkList = artworkList
    );
    for (let artwork of this.artworkList) {
      console.log(artwork.name);
  }

由于某种原因,我的控制台始终出现此错误:

错误TypeError:“ _ a未定义”

2 个答案:

答案 0 :(得分:2)

您的循环是同步运行的,而您则获取异步迭代的数据。 您将必须将实际循环移至then块中,以免访问可能的undefined值。

constructor(private artworkService: ArtworkService) {
}

ngOnInit() {
  this.refresh();
}

refresh() {
  this.artworkService.retrieveAll().then((artworkList) => {
    this.artworkList = artworkList;
    for (let artwork of this.artworkList) {
      console.log(artwork.name);
    }
  });
}

答案 1 :(得分:1)

.retriveAll()方法是一个承诺,您必须先使用await方法,然后再尝试使用this.artworkList,也可以将以下内容放入调用的.then部分中

for (let artwork of this.artworkList) {
  console.log(artwork.name);
}

当前,循环与对返回Promise的方法的调用一起异步运行,该方法试图通过空的this.artworkList循环,从而导致问题。