Property 'error' does not exist on type '“” | Promise'

前端 未结 3 1421
长发绾君心
长发绾君心 2021-02-13 18:03

I\'m trying to add some error handling to a service, following the Angular guide.

Relevant snippet:

private handleError (error: Response | any) {
  // I         


        
相关标签:
3条回答
  • 2021-02-13 18:36

    Same thing just happened to me. This happens when you fail to import the Response object.

    import { Response } from '@angular/http';
    
    0 讨论(0)
  • 2021-02-13 18:37

    No, it won't work because you wrote:

    const body = error.json() || '';
    

    Which means that body can be an empty string, and a string doesn't have the error property.

    This should be better:

    const body = error.json() || { error: null };
    

    Edit

    Oh, error.json() returns a Promise, which means that you won't be able to use this synchronous block, instead you'll need to:

    error.json().then(body => {
        if (!body) {
            body = "";
        }
    
        const err = body.error || JSON.stringify(body);
        const errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    });
    
    0 讨论(0)
  • 2021-02-13 18:37

    I had the same issue, I finally found this solution.

    .catch(error => {
      let errMsg: string;
      const body = JSON.parse(error._body);
      if (body) {
        errMsg = body.error
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error(errMsg);
      return Promise.reject(errMsg);
    });

    0 讨论(0)
提交回复
热议问题