订阅订阅angular2

时间:2020-06-12 08:43:41

标签: angular rxjs

我想使用第二个订阅中第一个订阅中的数据。 我收到了包含“文章”字段的回复,收到之后,我应该再次请求设置article.author值。

    if (!this.article) {

        this.articleSubscription = this.route.paramMap
            .pipe(
                switchMap(params => {
                    this.isLoadingInProgress = true;
                    return this.dataService.getArticleById(params.get('id'));
                }),
            ).subscribe(response => {
                this.article = response.currentArticle;
                this.article.relatedArticles = response.relatedArticles;

                this.userService.getAllUsers$().subscribe(users => {
                    const author: AlArticleAuthor =
                        users.find(user => user.id === this.article.userId);
                    this.article.author = {
                        firstName: author.firstName,
                        lastName: author.lastName,
                        organization: author.organization,
                        title: author.title,
                    };
                });
                this.isLoadingInProgress = false;
                super.setTitle(this.article.title);
                super.setMetaDescription(this.article.description);
                this.changeDetection.markForCheck();
            });
    }

2 个答案:

答案 0 :(得分:0)

答案已经在问题中了。您只需要使用其他switchMap。尝试以下

if (!this.article) {
  this.articleSubscription = this.route.paramMap.pipe(
    take(1),     // <-- use the first notification and complete
    switchMap(params => {
      this.isLoadingInProgress = true;
      return this.dataService.getArticleById(params.get('id')).pipe(
        switchMap(article => {     // <-- map the 1st API observable to 2nd API observable
          this.article = article.currentArticle;
          this.article.relatedArticles = article.relatedArticles;
          return this.userService.getAllUsers$();
        })
      )
    })
  ).subscribe(users => {
      const author: AlArticleAuthor = users.find(user => user.id === this.article.userId);
      this.article.author = {
        firstName: author.firstName,
        lastName: author.lastName,
        organization: author.organization,
        title: author.title,
      };
    },
    error => {
      // handle error
    },
    () => {     // <-- `complete` callback - executed when the HTTP request is complete
      this.isLoadingInProgress = false;
      super.setTitle(this.article.title);
      super.setMetaDescription(this.article.description);
      this.changeDetection.markForCheck();
    }
  );
}

答案 1 :(得分:0)

使用mergeMap。 将一个api数据发送到另一api数据非常有用。我附上了该代码的工作屏幕截图。 不要忘记从rxjs导入mergeMap。 干杯!

map(users => {
const user = users[0];
return user;
}),
mergeMap(user=> this.http.get(`https://secondapicall.com?userId=${user.id}`))).subscribe(posts=> {console.log(posts)});```