Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

asynchronous - Angular - two subscriptions in ngOnInit result in object 'undefined'

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to return observables in a sequential manner, you shouldn't nest your subscribe() methods. Instead, we should be using RxJS's mergeMap to map over the observable values from the activatedRoute into an inner observable, which is assigned to the newsID property. Then, we call the getSectors() method from _newswireService, and the observables are returned in subscribe() on the subsequent line. This way, your news will not be undefined.

Do not forget to import mergeMap onto your component!

import { mergeMap } from 'rxjs/operators';

//.
//.

this._activatedRoute.paramMap.pipe(
  mergeMap(params => {
    this.newsID = params.get('id');
    return this._newswireService.getSectors();
  })
).subscribe(res => {
  this.news = news;
  this.navigateToArticle();
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...