仅在可观察流为空时显示div

时间:2016-12-25 16:10:40

标签: angular observable

我正在使用类似于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>

1 个答案:

答案 0 :(得分:5)

在你的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>