码迷,mamicode.com
首页 > Web开发 > 详细

[Angular] Handle HTTP Errors in Angular with HttpErrorResponse interface

时间:2018-02-14 21:05:10      阅读:1297      评论:0      收藏:0      [点我收藏+]

标签:const   sub   error   end   sid   message   nbsp   mon   fail   

When communicating with some backend API, data travels over the network using the HTTP protocol. As such, failures may occur, be it on our own device (i.e. the browser) or on the server-side which may not be available or unable to process our request. We need to handle such error responses and give the user a proper feedback.

 

import { HttpErrorResponset } from ‘@angular/common/http‘;


export class AppComponent {
  people;
  message;
  constructor(private peopleService: PeopleService) {}

  fetchPeople() {
    this.peopleService
      .fetchPeople()
      .subscribe(
        (data) => {
          this.message = null;
          this.people = data;
        },
        (err: HttpErrorResponse) => {
          if (err instanceof Error) {
            // client-side error
            this.message = `An error occured ${err.error.message}`;
          } else {
            this.message = `Backend returned error code ${err.status}, body was: ${err.message}`;
          }
        }
      );
  }
}

 

[Angular] Handle HTTP Errors in Angular with HttpErrorResponse interface

标签:const   sub   error   end   sid   message   nbsp   mon   fail   

原文地址:https://www.cnblogs.com/Answer1215/p/8448860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!