简体   繁体   English

如何使用异步管道而不是使用订阅?

[英]How do I use async pipe instead of using subscribe?

I would like to use the async pipe "| async" instead of subscribing.我想使用异步管道“| async”而不是订阅。 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">在我的模板中,我有: <mat-card *ngIf="quiz.quizId === quizName">

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.请注意,每次您在模板中使用异步管道时,它都会进行订阅。

Add variable:添加变量:

quizName$ = this.activatedRoute.url.pipe(map(segments => segments[1].toString()));
  1. no need for takeUntil such as "| async" does it不需要takeUntil类的 "| async" 这样做
  2. optional(your IDE would know about it by itself)可选(你的 IDE 会自己知道)
quizName$: Observable<string> ...

in HTML:在 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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