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

爷,独闯天下 提交于 2019-12-05 01:01:10
Atais

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 {
}

I have the same problem while using angular2.0.0-beta.15

It seems like this is a bug. You get http status 200 and this is not correct:

https://github.com/angular/http/issues/54

Well i have faced something similar before. I was trying to make a logging Service and a Error handling which tells the user if error happened with some requests to the server or if the whole server is down.

I used HTTP Interceptor to catch the responses here is the code:

export class HttpErrorHandlingInterceptor implements HttpInterceptor {
   constructor(private logService: LogService,
               private layoutStateService: LayoutStateService){}
   intercept(
      req: HttpRequest<any>,
      next: HttpHandler
   ): Observable<HttpEvent<any>> {
     if (req.url) {
         return next.handle(req).pipe(
                map((event: HttpEvent<any>) => {
                   if (event instanceof HttpResponse) {
                        return event;
                   }
                }),catchError(err => {
                    if(!err.status){
                       this.layoutStateService.dispatchServerDown();
                    }else{
                       this.layoutStateService.dispatchAddServerError(err);
                       this.logService.logError(err);
                    }

               throw err;
             })
        );
    }
  }
}

Now you can specify what should happen when Server is down according to your application. Hope that helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!