1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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"

4 Comments

Thank you, but I'm going the previous solution because it's simpler and I'm retrieving quizId from a for loop in the template.
np ;) tip: loops, ifs, etc - it is mixing imperative and reactive(rx)/functional programming. it is possible to arrange streams with different operators(and creational observables).
about quiz - though it was Input
@andriishupta Thanks for your answer ! I didn't know async pipe could manage takeUntil :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.