2016-11-16 2 views
-2

각도 2로 확대되었습니다. 전체보기/구성 요소에서 발생하는 메시지를 표시하는 전역 오류 구성 요소에 대해 작업하고 있습니다.글로벌 구성 요소에 각도 2 푸시 메시지

어떻게 다른 구성 요소에서 전역 오류 구성 요소를 통신 할 수 있습니다. **

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

내가 다른 구성 요소 (안 응용 프로그램 구성 요소에서)에서 푸시 메시지를하려합니다.

메시지를 다른 구성 요소의 알림 구성 요소로 푸시 (Push)하려면 어떻게해야합니까?

+0

귀하의 코드를 작성하고 직접적으로 처리 할 수있는 특정 질문을하십시오. –

+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'); 
관련 문제