Angular 2将消息推送到全局组件

时间:2016-11-16 16:16:24

标签: angular

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

我正在尝试从其他组件推送消息(而不是来自应用组件)。

如何将消息从另一个组件推送到通知组件?

1 个答案:

答案 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');