我是 Angular 和 Typescript 的新手。如果在基于 id 的对象数组中找到对象,我尝试将 bool 变量设置为 true。下面显示的方法是从 ngOnInit() 调用的。
getTheatre(){
this.mChandigarh=false;
this.mBangaluru=false;
this.mChennai=false;
this.flag="Came to method call";
for(let i=0; i<this.mChandigarhArr.length; i++){
this.flag1="Came to chandigarh index"+i;
if(this.mChandigarhArr[i].movieid===this.movie.id){
this.flag2="ids matched";
this.mChandigarh=true;
break;
}
}
}
数组 mChandigarhArr 具有与给定条件匹配的元素,因此 mChandigarh 变量应设置为 true。
但是代码本身似乎并没有进入循环。标志显示在 UI 中,但 flag1 和 flag2 根本不显示。
早些时候我也尝试过使用 mChandigarhArr.findIndex() 。这对我来说没有成功。
<<=== 添加 ngOnInit() 代码=====>
ngOnInit() {
this.getChandigarhTheatre();
console.log(this.mChandigarhArr); //Shows the array is empty here
this.getTheatre(); // If i call this method from a click event in template then it works
}
getChandigarhTheatre(){
this.movieService.getChandigarhMovies().subscribe(
theatres => this.mChandigarhArr=theatres,
err => this.errMsg = <any>err
);
}
最佳答案
我怀疑您的 mChandigarhArr
为空。这可以解释为什么你永远不会进入循环。
尝试在循环之外使用 console.log(this.mChandigarhArr)
进行确认。
编辑:
您的 getChandigarhTheatre()
函数是异步的,这意味着:您不知道数据何时可用。
在您的代码中,您调用了 this.getTheatre()
但您的 getChandigarhTheatre()
尚未完全完成,并且 theatres => this.mChandigarhArr = Theaters
甚至还没有执行。这就是为什么你的数组是空的。
当您确定回调已完成时,您必须将调用移至 getTheatre()
。
幸运的是,subscribe()
运算符采用第三个参数 onCompleted您可以在其中调用 getTheatre()
:
getChandigarhTheatre(){
this.movieService.getChandigarhMovies().subscribe(
theatres => this.mChandigarhArr=theatres,
err => this.errMsg = <any>err,
() => this.getTheatre()
);
}
另外,题外话,但我建议尽可能多地使用空格来创建 code more readable .
在 Typescript 中,您还可以使用 let ... of ...
语句来代替老式的 for (i ; i++)
:读 this .
关于javascript - typescript for 循环不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49553598/