角度可观察取决于其他可观察对象

时间:2020-10-23 11:23:09

标签: angular rxjs observable

我将在需要的地方渲染页面

  1. 从路由器获取ID(使用this.route.params)
  2. 使用步骤1中的ID获取产品
  3. 使用步骤2中产品中的ID获取额外的数据

现在我可以通过执行以下操作来解决此问题:

this.article$ = this.route.params.pipe(
  map(params => params['articleId']),
  switchMap(productId => this._articleService.getArticle(productId))
);

this.article$.subscribe(article => {
  this.articleFormComponents$ = this._articleService.getArticleForm(article.form.id)
    .pipe(
      map(form => JSON.parse(form) as ArticleForm)
    );
});

对我来说这看起来很混乱。我应该如何改善呢?

1 个答案:

答案 0 :(得分:0)

jonrsharpe是正确的,但是要使它具体化,您可以这样做:

this.article$ = this.route.params.pipe(
  map(params => params['articleId']),
  switchMap(productId => this._articleService.getArticle(productId))
);

this.articleFormComponent$ = this.article$.pipe(
  switchMap(article => this._articleService.getArticleForm(article.form.id)),
  map(form => JSON.parse(form) as ArticleForm),
);

确保您订阅了每个流以查看结果。