首页 > Web开发 > 详细

[Angular] Handle HTTP Errors in Angular with HttpErrorResponse interface

时间:2018-02-14 21:00:20      阅读:303      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!