Reputation: 499
I am new to Angular and Typescript. I am trying to set boolean variable to true if an object is found in an array of objects based on id. The method shown below is called from 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;
}
}
}
The array mChandigarhArr has the element which matches the given condition , hence the mChandigarh variable should be set to true.
However the code does not seem to go in the loop itself. The flag gets shown in UI, but flag1 and flag2 are not at all shown.
Earlier i had tried using mChandigarhArr.findIndex() as well. It did not work out for me.
<<=== Adding ngOnInit() code=====>
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
);
}
Upvotes: 0
Views: 2113
Reputation: 315
I suspect your mChandigarhArr
to be empty. That would explain why you never enter the loop.
Try to console.log(this.mChandigarhArr)
outside your loop to be sure.
EDIT :
Your getChandigarhTheatre()
function is asynchronous, which means : you don't know when your data will be available.
In your code, you call this.getTheatre()
but your getChandigarhTheatre()
hasn't fully completed, and theatres => this.mChandigarhArr = theatres
hasn't even be executed. That's why your array is empty.
You have to move your call to getTheatre()
when you're sure your callback has been completed.
Fortunately, the subscribe()
operator takes a third parameter, onCompleted where you could call getTheatre()
:
getChandigarhTheatre(){
this.movieService.getChandigarhMovies().subscribe(
theatres => this.mChandigarhArr=theatres,
err => this.errMsg = <any>err,
() => this.getTheatre()
);
}
Also, off topic but I would suggest to use spaces as much as you can to make your code more readable.
In Typescript you can also make use of let ... of ...
statement instead of the oldschool for (i ; i++)
: read this.
Upvotes: 2