我正在使用类似于 angular2 heros 的文本搜索功能教程,但在用户未搜索时隐藏 div 时遇到问题。我的组件中有以下代码:
searchLocations: Observable<Location[]>;
private searchTerms = new Subject<string>();
// ...
ngOnInit(): void {
// ...
this.searchLocations = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term
? this.locationSearchService.search(term)
: Observable.of<Location[]>([]))
.catch(error => {
console.error(error);
return Observable.of<Location[]>([]);
});
}
然后在我的 html 中,我显示用户搜索的结果
<div class="results">
<div *ngFor="let loc of searchLocations | async" class="search-result">
{{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }}
</div>
</div>
但是使用我当前的代码,
results
div 是 总是 展示。如何检查可观察流何时为空?我试过 .count()
和 .length()
,但是这两个也返回可观察的......我想我需要做一些类似的事情:<div class="results" *ngIf="???">
<!-- ... -->
</div>
最佳答案
在您的 ngIf 指令中,您还应该使用异步管道,因为这是 Observable:
<div class="results" *ngIf="!(searchLocations | async)?.length">
<div *ngFor="let loc of searchLocations | async" class="search-result">
{{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }}
</div>
</div>
关于angular - 仅当可观察流为空时才显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322659/