简体   繁体   English

打字稿循环不起作用

[英]Typescript loop does not work

I'm trying to iterate over an array, but Angular refuses to step in into it... 我正在尝试遍历数组,但是Angular拒绝介入其中...

The array is being filled as follows. 数组按以下方式填充。 As you can see, I'm printing it into the console, and I can see that the array was initialized and filled. 如您所见,我将其打印到控制台中,并且可以看到该数组已初始化并填充。

export class CarDetailsComponent implements OnInit, AfterViewInit {
  cars: Array<Car>;

  constructor(private carService: CarService) {}

  ngOnInit() {
      this.cars = this.carService.getCars();
      console.log(this.cars);
  }
}

The array will be consumed into a ngAfterViewInit() . 该数组将被消耗到ngAfterViewInit() For debug purposes, the first thing that I did was to check if the array is ok. 出于调试目的,我要做的第一件事是检查数组是否正常。 And it is. 是的。 But, the console.log inside the loop is never called. 但是,永远不会调用循环内的console.log。 Why? 为什么?

ngAfterViewInit() {
  console.log(this.cars);
  for (let i in this.cars) {
    console.log(i);
  }
}

I also tried to for..of , this.cars.slice() and everything seems to be ok... 我也尝试了for..ofthis.cars.slice() ,一切似乎this.cars.slice() ...

EDIT (addressing some suggestions in comments) 编辑(解决评论中的一些建议)

I added both log suggestions and they show that the array is empty. 我添加了两个日志建议,它们表明该数组为空。 I've attached a printscreen that shows that console.log(this.cars) shows a valid array, but this.cars.length and JSON.stringify(this.cars) doesn't. 我附加了一个console.log(this.cars) ,该console.log(this.cars)显示console.log(this.cars)显示有效数组,但是this.cars.lengthJSON.stringify(this.cars)没有。

Since I'm noob, I don't know why this behavior occurs. 由于我是菜鸟,所以我不知道为什么会发生这种现象。 Probably it related with what @Ayman and @Codeepic pointed out. 可能与@Ayman和@Codeepic指出的内容有关。

PRINTSCREEN

EDIT 2 编辑2

Regarding @Minko question, I think that it is synchronous. 关于@Minko问题,我认为它是同步的。 It looks like: 看起来像:

  getCars(): Array<Car> {
    var cars: Car[] = [];
    this.http.get('//localhost:8080/cars).subscribe(data => {
      for (let entry of <Array<any>>data) {
        cars.push(entry);
      }
    });
    return cars;
  }

carService.getCars() method is asynchronous. carService.getCars()方法是异步的。 ngAfterViewInit runs after the template was rendered but before the carService.getCars() returns any results. ngAfterViewInit在渲染模板之后但在carService.getCars()返回任何结果之前运行。 That's why you don't see the console.log in for loop. 这就是为什么您看不到console.log登录for循环的原因。

发生这种情况的原因是,您正在进行http调用(您的get),并且在获得答案之前,您尝试使用响应对象,请将您的逻辑放入订阅中。

your method 你的方法

getCars(): Array<Car> {
    var cars: Car[] = [];
    this.http.get('//localhost:8080/cars).subscribe(data => {
      for (let entry of <Array<any>>data) {
        cars.push(entry);
      }
    });
    return cars;
  }

will very likely always return an empty array. 将很可能总是返回一个空数组。 That is because the http request will take a while to get the cars from the server. 这是因为http请求将需要一些时间才能从服务器获取汽车。 Also since you can call an asynchronous call in javascript it will not wait until it gets a result and return it. 另外,由于您可以使用javascript调用异步调用,因此它不会等到得到结果并返回它。

To wait until your array is filled you can use Promises. 要等待阵列填满,可以使用Promises。

getCars(): Promise<Car[]> {
    return new Promise (allLoadedFromServer => {
      var cars: Car[] = [];
      this.http.get('//localhost:8080/cars).subscribe(data => {
        for (let entry of <Array<any>>data) {
          cars.push(entry);
        }
        allLoadedFromServer(cars);
      });
    }
  }

now you can access the data via: 现在您可以通过以下方式访问数据:

ngAfterViewInit() {
  this.getCars().then(data=>{
     this.cars = data;
     for (let i of this.cars) {
       console.log(i);
     }
   );
}

that should give you the expected result. 那应该给你预期的结果。 Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM