Angular - ngOnInit 中的两个订阅导致对象 'undefined'

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

简而言之..我无法访问我的新闻对象。在函数中调用时返回 'undefined'。

在我的 ngOnInit 中,我有两个订阅。 第一个 returns 新闻对象(在组件顶部定义为全局变量)。

第二次订阅returns一个路由参数,然后触发一个函数(navigateToArticle)。

现在...当第二个订阅触发 'navigateToArticle' 函数时,我希望该函数能够访问新闻对象。

但是,每次我尝试控制台记录新闻对象时,它都会返回 'undefined'。 现在我明白这与订阅是异步的有关。

所以我的问题是,如何确保新闻对象已加载并可供 'navigateToArticle' 函数访问。 可能是某种检查以查看新闻是否已加载?

抱歉,我是 Angular 的新手,请放轻松。我确定我遗漏了一些非常简单的东西。 为了清楚起见,我已将代码精简到最低限度。

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

如果您想 return 以顺序方式观察,则不应嵌套 subscribe() 方法。相反,我们应该使用 RxJS 的 mergeMap 将来自 activatedRoute 的可观察值映射到一个内部可观察值,它被分配给 newsID 属性。然后,我们从 _newswireService 调用 getSectors() 方法,并在后续行的 subscribe() 中对可观察对象进行 returned。这样,您的 news 就不会未定义。

不要忘记将 mergeMap 导入到您的组件中!

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