Angular – two subscriptions in ngOnInit result in object ‘undefined’

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

Leave a Comment