繁体   English   中英

HTTP响应错误处理Angular应用程序

[英]HTTP Response Error Handling Angular Application

我有一个data.json文件,如下所示。

[
    {"value":1},
    {"value":2},
    {"value":3},
    {"value":3}
]

&我正在使用Http获取数据。 数据正常发送,但是如果我的服务器已关闭怎么办,它将引发错误,我想向用户显示一些自定义消息而不是该错误。 以下是我获取数据的函数。

 data: any;

  getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })
  }

  ngOnInit() {
    this.getData();
  }
  getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    },(err:HttpErrorResponse)=>{handle your error here});

订阅接受错误处理回调作为第二个参数。 您可以在此处查看API详细信息

https://angular.io/api/common/http/HttpErrorResponse

您还可以使用rxjs提供的catchError运算符

import {catchError} from 'rxjs/operators'

this.http.get('http://localhost/php/data.json')
    .pipe ( 
       catchError((error) => // handle the error here; )
     )
    .subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })

如果要捕获特定实例,则:

getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    }, (err:HttpErrorResponse) => {
        consdole.log(err)
     })
  }

我建议您使用intercepter集中处理error

http-intercepter.ts:

import { Injectable, Injector } from '@angular/core';
import {
    HttpEvent,
    HttpHeaders,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpRequest
} from '@angular/common/http';



import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(
        private appService: AppService) {

    }

    /**
     * 
     * @param req - parameter to handle http request
     * @param next - parameter for http handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        /**
         * Handle newly created request with updated header (if given)
         */
        return next.handle(req).do((event: HttpEvent<any>) => {
            /**
             * Sucessfull Http Response Time.
             */
            if (event instanceof HttpResponse) {
                const elapsed = Date.now() - started;
            }

        }, (err: any) => {
            /**
             * redirect to the error_handler route according to error status or error_code
             * or show a modal
             */
            if (err instanceof HttpErrorResponse) {
                console.log(err);
            }
        });
    }

}

在module.ts中:

提供者:[

{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true,
}
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM