找不到搜索时出现angular2捕获错误

时间:2016-08-17 10:03:28

标签: angularjs angular

我尝试在找不到搜索时捕获angular2中的错误并显示有关错误的消息。我想我设法这样做了,但是当找到搜索时,错误信息仍在显示。

不确定这是否是在angular2中捕获错误的正确方法,但错误消息显示在搜索过程中未找到项目。

this._searchService.getProduct(queryString1)
        .subscribe(data => {
            if (data) {
                this.productObj = data;
                setTimeout(() => {
                    this.isLoading = false;
                    this.products = this.productObj;
                }, 500);
            }
        },
        err => {
            this.isLoading = false;
            this.errorMessage = "Sorry no item found, please check product Id";
            console.log(this.errorMessage);
        }
        );

HTML

<div *ngIf="!isLoading"> items will be here </div>
<h3 *ngIf="errorMessage">{{errorMessage}}</h3>

1 个答案:

答案 0 :(得分:0)

因为您没有在成功回调中添加this.errorMessage = false。因此,this.errorMessage的值在服务首次遇到错误时设置为true,并且由于您在成功期间未更新其值,因此错误消息始终可见

this._searchService.getProduct(queryString1)
        .subscribe(data => {
            this.errorMessage = false //add this to hide error message during success
            if (data) {
                this.productObj = data;
                setTimeout(() => {
                    this.isLoading = false;
                    this.products = this.productObj;
                }, 500);
            }
        },
        err => {
            this.isLoading = false;
            this.errorMessage = "Sorry no item found, please check product Id";
            console.log(this.errorMessage);
        }
);