Search code examples
jsonangularhttphandler

Angular 2 (TypeScript) Handle empty json Response from Http


i have this function

searching() {
 this._demoService.postData(this.url,this.searchtobesent).subscribe(
  data =>{
    this.listings=data;
    this.errorMsg="";
    if(data){
    }
    else{
      this.errorMsg="Nothing Found";
    }
  },
  error =>{
    console.log("error : "+error);
    this.errorMsg="Error Loading Your Listings";
  }
  ) ;
}

When there are some results from my backend (that are being sent in Json format) everything is ok. what i want is when the results are empty and i receive from the server this

[]

i want this.errorMsg to become Nothing Found. Any help would be appreciated ;) Thanks


Solution

  • Even it is an empty array, it is still a valid response. You can use array.length to handle this.

    if (data && data.length > 0) {
        // do something
    } else {
        this.errorMsg = "Nothing Found";
    }