【问题标题】:I want to display some useful information when my Observable returns empty当我的 Observable 返回为空时,我想显示一些有用的信息
【发布时间】:2017-03-04 06:35:56
【问题描述】:

我有一个主页,其中有一个搜索输入框,它会路由到另一个页面以显示结果。在该结果页面中,我有一个 *ngFor 循环通过返回的 observable (searchResult)。

我有一个<div *ngIf="searchResult">,它显示 observable 是否为空。但是在组件初始化的时候,从首页到结果页,这个div加载的很快,搜索结果返回后就消失了。有没有另一种方法来检查 Observable 是否为空,所以我可以只使用布尔值而不是使用这个 *ngIf="searchResult"。

这是我的订阅:

getDocument(searchText:string) {
        this._contractService.getDocument(searchText)
            .subscribe(
            document => this.document = document,
            error => this.errorMessage = <any>error);

    }

这是我的 *ngIf:

<div id="search-not-found" class="col-xs-12" *ngIf="!searchResult">
 <div class="alert alert-success" role="alert"><p>Sorry, we did not find any match related to your search"</p></div>
      </div>

如果有任何帮助,我将不胜感激。谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    我能够解决这个问题。我添加了一个布尔变量 (searchResultEmpty:boolean=false) 并将其初始化为 false。然后在我的订阅中,我将该布尔值更改为 true。

    这是我更新的订阅:

    getDocument(searchText:string) {
            this._contractService.getDocument(searchText)
                .subscribe(
                document => {this.document = document, this.searchResultEmpty=true},
                error => this.errorMessage = <any>error);
    
        }
    

    这里是 div:

    <div *ngIf="searchResultEmpty">
    <div id="search-not-found" class="col-xs-12" *ngIf="!searchResult">
     <div class="alert alert-success" role="alert"><p>Sorry, we did not find any match related to your search"</p></div>
          </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-09
      • 2017-02-27
      • 2020-06-30
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多