Angular 4 : get error message in subscribe

前端 未结 2 1008
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 03:03

In the service, there is this code :

  getUser(id){
    return this.http.get(\'http:..../\' + id)
      .map(res => res.json());
  }

In the

相关标签:
2条回答
  • 2021-02-01 03:48

    Sometimes when you call catch without using arrow function like below

    getUserList() {
        return this.http.get(this.constURL + '/loans/all', this.headerOptions)
        .catch(this.handleError);
    }
    
    handleError(error: Response) {
        if (error.status == 500) {      
          this.router.navigate(['/login']);
        } else {
          return Observable.throw(error);
        }
    }
    

    then it gives error of

    ERROR TypeError: Cannot read property 'navigate' of undefined not getting this

    Because in handleError function this object is not accessible..if you console this.router then you will get undefined.. so this object not working and not getting router all available methods

    So you have to use arrow function here like below

    getUserList() {
        return this.http.get(this.constURL + '/loans/all', this.headerOptions)
        .catch(error => { 
          return this.handleError(error);
        });
    }
    
    handleError(error: Response) {
        if (error.status == 500) {      
          this.router.navigate(['/login']);
        } else {
          return Observable.throw(error);
        }
    }
    

    Also if you have not mentioned return for handlerError function then it will throw error again like

    Argument of type '(error: any) => void' is not assignable to parameter of type

    So its necessary to type return for handlerError function.

    Check in details here . He has explained code very well with all possible errors and solution of that..worked for me

    0 讨论(0)
  • 2021-02-01 04:00

    (err) needs to be outside the customer fat arrow:

    this.myService.getUser(this.id).subscribe((customer) => {
      console.log(customer);
      this.customer = customer,
    },
    (err) => {console.log(err)});
    

    To get the error msg back, add a catch that will return the error object:

    getUser(id){
      return this.http.get('http:..../' + id)
        .map(res => res.json())
        .catch(this.handleError);
    }
    
    private handleError(error: any) { 
      let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
      return Observable.throw(error);
    }
    
    0 讨论(0)
提交回复
热议问题