简体   繁体   中英

subscribe in subscribe angular2

I want to use data from the first subscribe in the second subscribe. I received response, that have field 'article', and after I have received it, I should do another request to set article.author value.

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

The answer is already in the question. You just need to use an additional switchMap . Try the following

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

use mergeMap. It is very useful to send one api data to another api data. I attached working screenshot of the code. Don't forget it to import mergeMap from rxjs. Cheers!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM