2016-11-16 1 views
-2

Новое в Angular 2. Я работаю над компонентом глобальной ошибки, который покажет ошибку сообщений со всех видов/компонентов.Угловые 2 push-сообщения глобальному компоненту

Как я могу общаться глобальный компонент ошибки из другого компонента. **

// appComponent.ts 
appComponet will have several components 
    @Component({ 
     selector: 'app', 
     template: ` 
      <notification-component></notification-component> 
      <header-component></header-component> 
      <router-outlet></router-outlet> 
      <footer-component></footer-component> 
    }) 
    **I like to push messages to notification-component. 
    here is the notificationComponent** 
    import { Component, OnInit } from '@angular/core'; 
    @Component({ 
     selector: 'notification-component', 
     templateUrl:"app/notification/notification-view.component.html", 
     styleUrls:["app/notification/css/notification-view.component.css"] 
    }) 
    NotificationViewComponent will have notificationMessages 
    export class NotificationViewComponent implements OnInit { 
     notificationMessages = []; 
     hideNotification: boolean = false; 
     ngOnInit(): void { 
      this.notificationMessages.push("We arre sorry -- an error occurred while one of your request. "); 
     }  
     hideNotificationSection() { 
      this.hideNotification = true; 
     } 
    } 

Я пытаюсь нажать сообщения от другого компонента (не из приложения Component).

Как я могу передать сообщения компоненту уведомления из другого компонента?

+0

rmat ваш код и задать конкретный вопрос, который может быть непосредственно адресован. –

+0

Я новичок в этом форуме. я постараюсь улучшить –

ответ

0

Сообщите об ошибках Службе, имеющей общие для всех компонентов. Используйте класс rxjs/Subject для «испускания» ошибки для любого компонента, подписанного на нее.

Вам понадобится 2 импорта.

import { Subject } from 'rxjs/Subject'; // to emit errors 
import { Subscription } from 'rxjs/Subscription'; // to subscribe to the emiter 

Вот и пример службы ошибки:

@Injectable() 
export class ErrorService { 

    public subject_error: Subject<string> = new Subject(); 

    public addError(error: string){ 
     subject_error.next('error'); 
    } 
} 

Подписаться на эту тему, где вы хотите (не забудьте отменить подписку):

@Component({ 
    ... 
}) 
export class MyComponent OnInit, OnDestroy { 

    private subscription:Subscription = new Subscription(); 

    constructor(
     private errorService: ErrorService, 
    ) {} 
    ngOnInit(){ 
     this.subscription = this.errorService.subject_error.subscribe(
      error => console.log(error) 
     ); 
    } 
    ngOnDestroy(){ 
     this.subscription.unsubscribe(); 
    } 
} 

Добавление об ошибке так же просто:

this.errorService.addError('an error occurred'); 
Смежные вопросы