A
A
Alexey Miroshnichenko2018-10-12 10:46:00
Angular
Alexey Miroshnichenko, 2018-10-12 10:46:00

How to properly make a subscribe inside another subscribe?

addPost() {
    this.openDialog().subscribe(formData => {
      if (formData) {
        this.postsService.add(formData).subscribe((res: Post) => {
          this.posts.unshift(res);
        });
      }
    });
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dasha Tsiklauri, 2018-10-12
@asdqwee

don't do that, use flatMap

this
  .openDialog()
  .flatMap(fd=>{
     return !fd?Observable.Empty():this.postsService.add(fd).first();
  })
  .subscribe(post=>{
    this.posts.unshift(post);
  });

K
kimisu, 2018-11-15
@kimisu

maybe like this

async addPost() {
   const formData = await this.openDialog().toPromise();
   if (formData) {
    const res = await this.postsService.add(formData).toPromise();
     this.posts.unshift(res);
   }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question