【发布时间】:2021-02-09 16:58:48
【问题描述】:
有以下代码,我想知道 为什么 Subject.next(1) 发射在模板中不可见,而 BehaviorSubject.next() 发射是可见的。
我知道将它包装在 setTimeout() 中可以解决问题,但我想了解它。
我好像Subject.next() 是同步 并且async 管道没有接收/标记检查。
@Component({
selector: 'my-app',
template: `
<div>Subj: {{ subj$ | async }}</div>
<div>BehavSubj: {{ behavSubj$ | async }} </div>
<div>Interval: {{ interval$ | async }} </div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
subj$ = new Subject<number>();
behavSubj$ = new BehaviorSubject<number>(1);
interval$ = interval(1000).pipe(take(100));
ngOnInit(): void {
this.subj$.next(1);
this.behavSubj$.next(2);
}
}
https://stackblitz.com/edit/angular-ivy-crnfgc?file=src/app/app.component.ts
【问题讨论】:
-
阅读主题。他们不会向迟到的订阅者发出最后发出的值。您的异步管道订阅是在下次通话后进行的
-
未检测到,因为时间太早了。将所有出现的
OnInit替换为AfterViewInit即可。 -
一个 BehaviorSubject 有 replay 行为,而普通的 Subject 没有。
-
我还没有意识到,这是时间问题????♂️,谢谢您的解释。
标签: angular async-pipe