Angular2 HTTP - How to understand that the backend server is down

后端 未结 3 1508
我在风中等你
我在风中等你 2021-02-19 07:55

I am developing a front end which consumes JSON services provided by a server.

I happily use HTTP of Angular2 and I can catch errors via .catch() operator.

3条回答
  •  不思量自难忘°
    2021-02-19 08:43

    If you would like to handle this event globally in your application I recommend using slightly modified Nicolas Henneaux's answer https://stackoverflow.com/a/37028266/1549135

    Basically you can check for error.status === 0 which happens when the net::ERR_CONNECTION_REFUSED error occurs.

    The complete module file:

    import { Request, XHRBackend, BrowserXhr, ResponseOptions, XSRFStrategy, Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    
    export class AuthenticationConnectionBackend extends XHRBackend {
    
      constructor(_browserXhr: BrowserXhr, _baseResponseOptions: ResponseOptions, _xsrfStrategy: XSRFStrategy) {
        super(_browserXhr, _baseResponseOptions, _xsrfStrategy);
      }
    
      createConnection(request: Request) {
        let xhrConnection = super.createConnection(request);
        xhrConnection.response = xhrConnection.response.catch((error: Response) => {
          if (error.status === 0){
            console.log("Server is down...")
          }
          ...
          return Observable.throw(error);
        });
        return xhrConnection;
      }
    
    }
    

    Module file:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { HttpModule, XHRBackend } from '@angular/http';
    import { AppComponent } from './app.component';
    import { AuthenticationConnectionBackend } from './authenticated-connection.backend';
    
    @NgModule({
        bootstrap: [AppComponent],
        declarations: [
            AppComponent,
        ],
        entryComponents: [AppComponent],
        imports: [
            BrowserModule,
            CommonModule,
            HttpModule,
        ],
        providers: [
            { provide: XHRBackend, useClass: AuthenticationConnectionBackend },
        ],
    })
    export class AppModule {
    }
    

提交回复
热议问题