Search code examples
javascriptangularrxjsangular-pipe

How do I use async pipe instead of using subscribe?


I would like to use the async pipe "| async" instead of subscribing. This is what my subscription code currently looks like:

ngOnInit(): void {
  this.activatedRoute.url
    .pipe(takeUntil(this.unsubscribe$))
      .subscribe(segments => {
        this.quizName = segments[1].toString();
      });
}

and in my template I have: <mat-card *ngIf="quiz.quizId === quizName">


Solution

  • Let's try this :

    quizName$: Observable<any>;
    
    ngOnInit(): void {
      this.quizName$ = this.activatedRoute.url
        .pipe(
          takeUntil(this.unsubscribe$),
          map(segments => segments[1].toString()); // Not sure about this part
        );
    }
    
    <mat-card *ngIf="(quizName$ | async) === quiz.quizId">
    

    Be careful, everytime you will use async pipe in your template, it will make a subscribe.