首页 > 解决方案 > Angular observable 依赖于其他 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)
    );
});

这对我来说看起来很乱......我应该如何改进这个?

标签: angularrxjsobservable

解决方案


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

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


推荐阅读