In short.. I am not able to access my news object. It is coming back as 'undefined' when called in a function.
In my ngOnInit I have two subscriptions.
First one returns a news object (which is defined as a global variable at the top of the component).
The second subscription returns a route parameter and then triggers a function (navigateToArticle).
Now... when the second subscription triggers the 'navigateToArticle' function, I want that function to be able to access the news object.
However, every time I try to console log the news object, it comes back as 'undefined'.
Now I understand that this is something to do with the subscriptions being asynchronous.
So my question is, how can I ensure that the news object has been loaded and accessible to the 'navigateToArticle' function.
Possibly some kind of check to see if news has been loaded?
Sorry, I'm new to Angular so please go easy. I'm sure I'm missing something very simple.
I've stripped code down to bare minimum for clarity.
public news: Newswire;
ngOnInit() {
this._newswireService.getSectors().subscribe((news: Newswire) => {
this.news = news;
}
this._activatedRoute.paramMap.subscribe(params => {
this.newsID = params.get('id');
this.navigateToArticle();
})
}
public navigateToArticle() {
console.log(this.news);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…