循环的typescript不执行

时间:2018-03-29 10:21:01

标签: javascript typescript angular5

我是Angular和Typescript的新手。如果在基于id的对象数组中找到对象,我试图将boolean变量设置为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()。它对我来说没有用。

&lt;&lt; ===添加ngOnInit()代码=====&gt;

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
    );
  }

1 个答案:

答案 0 :(得分:1)

我怀疑你的mChandigarhArr是空的。这可以解释为什么你永远不会进入循环。

在循环外尝试console.log(this.mChandigarhArr)以确定。

编辑:
您的getChandigarhTheatre()功能是异步的,这意味着:您不知道您的数据何时可用。

在您的代码中,您致电this.getTheatre()getChandigarhTheatre()尚未完全完成,theatres => this.mChandigarhArr = theatres甚至无法执行。这就是你的阵列为空的原因。

当您确定您的回调已完成时,您必须将来电移至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 ...语句而不是oldschool for (i ; i++):阅读this

相关问题