integral100x
integral100x

Reputation: 342

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">

Upvotes: 1

Views: 1055

Answers (2)

andriishupta
andriishupta

Reputation: 577

Add variable:

quizName$ = this.activatedRoute.url.pipe(map(segments => segments[1].toString()));
  1. no need for takeUntil such as "| async" does it
  2. optional(your IDE would know about it by itself)
quizName$: Observable<string> ...

in HTML:

*ngIf="(quizName$ | async) === quiz.quizId"

more "robust" solution

showQuiz$: Observable<boolean> = this.activatedRoute.url.pipe(
  map(segments => segments[1].toString()),
  map(quizName => quizName === this.quiz && this.quiz.id)
);
*ngIf="showQuiz$ | async"

Upvotes: 3

Emilien
Emilien

Reputation: 2761

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.

Upvotes: 3

Related Questions