nCore nCore - 3 months ago 8
AngularJS Question

angular2 catching error when search is not found

I'm trying to catch an error in angular2 when search is not found and showing a message about the error. I think I managed to do so but when the search is found the error message is still showing.

Not sure if that's a correct way of catching error in angular2, but the error message shows when item is not found during the search.

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>

Answer

Its because you didn't add this.errorMessage = false inside success callback. Hence value of this.errorMessagesets true when service first encounters error and since you're not updating its value during success , the error message is visible always

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);
        }
);
Comments