使用Angular 2全局显示http错误

时间:2016-07-15 15:54:47

标签: angular

我想为我的应用程序的所有页面显示全局http连接错误消息的弹出窗口。

有什么好办法吗?

2 个答案:

答案 0 :(得分:3)

您可以通过包含此自定义组件来创建自定义组件并在弹出窗口中显示错误列表。例如,你可以这样做

@Component({
     selector: 'list-errors',
     template: `<ul class="error-messages" *ngIf="errorList">
        <li *ngFor="let error of errorList">
            {{ error }}
        </li> </ul>`
    })
export class ListErrorsComponent {
  formattedErrors: Array<string> = [];

      @Input()
      set errors(errorList: Errors) {
        this.formattedErrors = [];

        if (errorList.errors) {
          for (let field in errorList.errors) {
            this.formattedErrors.push(`${field} ${errorList.errors[field]}`);
          }
        }
      };

      get errorList() { return this.formattedErrors; }
      }

在要显示错误列表的弹出窗口中使用此选项

   <list-errors [errors]="errors"></list-errors>

创建一个错误模型

  export class Errors {
  errors: {[key:string]: string} = {};
  }

设置error对象的值并将此错误对象传递给list-error组件

 errors: Errors = //assign your errors to this variable

答案 1 :(得分:1)

我找到了解决方案。

主要想法:将桥接服务 EventEmitter 一起使用。

api.provider.ts

import { Injectable, Output, EventEmitter } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';

@Injectable()
export class ApiProvider {
    private _host: string;

    @Output() errorHandled$ = new EventEmitter();

    constructor(private _http: Http) {
        this._host = "http://localhost:5000";        
    }

    private errorHandler(response: Response): any {        
        if (response.status == 0)
        {            
            this.errorHandled$.emit({
                value: "ERR_CONNECTION_REFUSED"
            });
        }
        return null;
    }

    get(path: string): Promise<any> {
        var headers = new Headers();

        return this._http.get(this._host + path, { headers: headers })
            .toPromise()
            .then(response => {                         
                return response.json();
            })
            .catch((response: Response) => this.errorHandler(response));
    }

    post(path: string, body: string): Promise<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this._http.post(this._host + path, body, { headers: headers })
            .toPromise()
            .then((response: Response) => {
                return response.json();
            })
            .catch((response: Response) => this.errorHandler(response));
    }
}

app.component.ts

import 'rxjs/Rx';
import { Component } from '@angular/core';

import { ApiProvider } from './providers/api.provider';

@Component({
    selector: 'mii-app',
    templateUrl: './app.component.html'
})
export class AppComponent {    
    globalErrors: string[];

    constructor(private _api: ApiProvider) {
        this.globalErrors = [];

        _api.errorHandled$.subscribe(value => { console.log('subscribe'); this.globalErrors.push('error connection.')});          
    }

    clearErrors(): void
    {
        this.globalErrors = [];
    }
}

app.component.html

<div *ngIf="globalErrors.length > 0" class="alert alert-danger fade in">
    <a (click)="clearErrors()" class="close" aria-label="close">&times;</a>
    error...
</div>

我们必须在main.ts中注册我们的ApiProvider,以便从依赖注入中获得单个实例。

main.ts

/// <reference path="../../typings/globals/core-js/index.d.ts" />

import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent } from './app.component';
import { ApiProvider } from './providers/api.provider';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    ApiProvider
])
.catch(err => console.error(err));