I have found a solution.
Main idea: use the bridge service with 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">×</a> error... </div>
We must register our ApiProvider in main.ts in order to have one instance from the dependency injection.
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));
source share