【问题标题】:Only show div when observable stream is empty仅在可观察流为空时显示 div
【发布时间】:2017-05-10 09:52:49
【问题描述】:

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

【问题讨论】:

标签: angular observable


【解决方案1】:

在您的 ngIf 指令中,您还应该使用异步管道,因为这是可观察的:

  <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>

【讨论】:

  • 请在您的代码 sn-p 中添加一些注释,以帮助 OP 了解您的解决方案的工作原理
  • 这似乎不起作用,给我error: cannot read property 'length' of null
  • 句法果糖这对我有用,它的 ?将处理 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多