2016-07-15 23 views

Trả lời

1

Tôi đã tìm thấy giải pháp.

Ý tưởng chính: sử dụng dịch vụ cầu với 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> 

Chúng ta phải đăng ký ApiProvider của chúng tôi trong main.ts để có một cá thể từ tiêm phụ thuộc.

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)); 
+0

Vẫn đang sử dụng theo cách này? Những nơi khác cho thấy bạn không nên đăng ký theo cách thủ công (http://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter) nhưng tôi chưa tìm thấy bất kỳ giải pháp thay thế nào cho câu hỏi của bạn. –

3

Bạn có thể tạo một thành phần tùy chỉnh và hiển thị danh sách các lỗi trong cửa sổ popup bằng cách bao gồm thành phần tùy chỉnh này. Ví dụ bạn có thể làm

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

này sử dụng này trong cửa sổ popup nơi bạn muốn hiển thị danh sách các lỗi

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

tạo ra một mô hình báo lỗi như vậy

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

đặt một giá trị đối tượng lỗi và chuyển đối tượng lỗi này đến thành phần lỗi danh sách

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

lỗi: Lỗi = // chỉ định lỗi của bạn cho biến này Xin chào, Bạn có thể hiển thị mẫu gán một số lỗi giả cho đối tượng lỗi không? tôi tiếp tục nhận được lỗi về nó. – Davvit

+0

@Davvit sử dụng đoạn mã này lỗi: Lỗi = {'error_code': 'chuỗi lỗi'}; –

Các vấn đề liên quan