我试图用Angular Async管道订阅行为对象/replaceAbject。另外,我必须使用堂或debouncetime操作员丢弃一些值。
这是一个示例(我使用了Angular CLI版本7.3.0并仅更改App.component):
import {Component, OnInit} from '@angular/core';
import {Observable, ReplaySubject, Subject} from 'rxjs';
import {auditTime, tap} from 'rxjs/operators';
@Component({
selector: 'app-root',
template: `{{value$ | async}}`,
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
private readonly subjectWithState: Subject<number>;
constructor() {
this.subjectWithState = new ReplaySubject(1);
}
ngOnInit(): void {
this.subjectWithState.next(42);
}
get value$(): Observable<number> {
return this.subjectWithState.asObservable()
.pipe(
tap(value => console.log(value)),
auditTime(1000),
);
}
}
问题在于主题不会停止发射(单个)值,而我没有任何输出(请参阅控制台日志)。一切都按预期工作,或者没有堂(1000)。
我找不到任何可以解释这种行为的东西。如何使用异步管和行为对象或replataySubject?
每次视图访问值$ $创建新观察值时。不要使用getter属性并创建属性,以便访问可观察的实例。
value$ = this.subjectWithState.asObservable()
.pipe(
tap(value => console.log(value)),
auditTime(1000),
);