当可观察对象发射时如何在不触发新发射的情况下获取值?我想在ngClass标记中获取可观察值。
我尝试使用管道水龙头来获取通过switchMap传递的值,但没有记录该值。然后,我可以将trueIfDefinitionsLength
用于ngClass条件。
this.definitions$.pipe(
tap(value => console.log('timer result =', value))
)
观察者订阅|异步
模板:
<input [ngClass]="{'input-has-results': trueIfDefinitionsLength > 0}"
[formControl]="searchInput">
<ng-container *ngIf="definitions$ | async as definitions">
<div class="format-options" *ngIf="definitions.length > 0">
<div *ngFor="let definition of definitions" class="search-result">
<div>{{definition.name}}</div>
<div>{{definition.description}}</div>
</div>
</div>
</ng-container>
组件
this.definitions$ = this.searchInput.valueChanges
.pipe(
tap(value => console.log('input')),
//startWith(''),
debounceTime(500),
//distinctUntilChanged(),
switchMap(value => this.definitionService.searchTerm(value))
);
答案 0 :(得分:5)
请改用BehaviorSubject
。它有一种方法getValue()
来获取当前值而不发出新值。
答案 1 :(得分:1)
ReplaySubject
在这种情况下也可能派上用场。它缓存n个最后的next
,然后为尚未见过的每个新订户重新发布它们。