Angular2 HTTP - 如何理解后端服务器已关闭

Pic*_*cci 14 angular2-http

我正在开发一个前端,它使用服务器提供的JSON服务.

我很高兴使用Angular2的HTTP,我可以通过.catch()运算符捕获错误.

如果我发现与特定服务相关的问题(例如,服务未由服务器定义),则catch()运营商会收到Response状态404,我可以轻松管理该情况.

另一方面,如果服务器完全关闭,则catch()操作员会收到带有状态代码的响应,200并且没有与问题原因相关的特定标志或文本(即整个服务器已关闭).在控制台上,我看到angular(http.dev.js)写了一条消息,net::ERR_CONNECTION_REFUSED但我不知道如何在我的代码中做一些类似的事情(即理解正在发生的事情并做出适当的反应).

任何帮助,将不胜感激.

Ata*_*ais 8

如果您想在您的应用程序中全局处理此事件,我建议使用略有修改的Nicolas Henneaux的答案/sf/answers/2591978651/

基本上,你可以检查error.status === 0时,这恰好net::ERR_CONNECTION_REFUSED发生错误.

完整的模块文件:

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

}
Run Code Online (Sandbox Code Playgroud)

模块文件:

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 {
}
Run Code Online (Sandbox Code Playgroud)


Her*_*sen 2

我在使用 angular2.0.0-beta.15 时遇到同样的问题

看来这是一个错误。您得到 http 状态 200,这是不正确的:

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

  • BTW 链接截至今天已损坏 (2认同)