How to apply Angular ErrorHandler accross modules

前端 未结 2 2013
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 19:55

Here\'s my Angular 4 app module:

@NgModule({
declarations: [
    AppComponent
],
providers: [
    QuickBoardListService,
    {provide: ErrorHandler, useClass         


        
2条回答
  •  暖寄归人
    2021-01-16 20:31

    In angular you can write interceptor to intercept http request. So the in the interceptor you can handle error for all http call from one place. I will work perfectly for all modules.

    interceptor for non HttpClient uses

    export class AppComponent implements OnInit {
          reqInterceptable: Interceptor = req => {
            if (req[1] && req[1].headers ) {
              // do what ever you want
            }
    
            return req;
          };
    
      respInterceptable: Interceptor, Observable> = res => res.do(null, e => {
        if (e.url) {
            this.alerter.alert(new DangerAlert('HTTP Error: ' + e.status + ' ' + e.statusText,
              'URL: ' + e.url, 'Info: ' + e.json().message));
        }
        return e;
      });
    
      constructor(private alerter: AlertService,
        public interceptor: HttpInterceptorService,
        private router: Router,
        private route: ActivatedRoute,
      ) {
        this.skipDictionary = {};
        // handled skipAlert flag for messaging of failed requests
        this.interceptor.request().addInterceptor(this.reqInterceptable);
    
        // for every request if we get an error notify the user of it
        this.interceptor.response().addInterceptor(this.respInterceptable);
      }
    }
    

    Interceptor for HttpClient

    This is for the new HttpClient and you can directly write the interceptor like below

    @Injectable()
    export class HttpsRequestInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        // do something for your error message
        return next.handle(dupReq);
      }
    };
    @NgModule({
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: HttpsRequestInterceptor, multi: true }
      ]
    })
    export class InterceptorModule { }
    

提交回复
热议问题