我在做什么Angular2 EventEmitter错误?

我在做什么Angular2 EventEmitter错误?

问题描述:

我想用angular2 EventEmitter创建通用烤面包服务。 我创建了一个服务并发出一些数据。我要赶在组件这个数据,但它不工作:/我在做什么Angular2 EventEmitter错误?

这是必须的服务发出事件:

import {EventEmitter, Injectable, Output} from "@angular/core"; 
import {IAlert} from "../../types/interfaces/IAlerts"; 

@Injectable() 
export class ExceptionsManagerConfig { 
public getalert(): IAlert { 
    return this._alert; 
} 

public setAlert(value: IAlert) { 
    this._alert = value; 
    this.alertChangeEvent.emit(value); 
    console.log("set alert"); 
} 

@Output() alertChangeEvent: EventEmitter<any> = new EventEmitter(); 
private _alert: IAlert; 
} 

而且这是必须的组件赶上事件:

import {Component, OnDestroy, OnInit, Input, EventEmitter} from "@angular/core"; 
import {ExceptionsManagerConfig} from "../../../../sheard/settings/exeptions/exeptions.menager.service.config"; 
import {IAlert} from "../../../../sheard/types/interfaces/IAlerts"; 
declare const Materialize: any; 

@Component({ 
    providers: [ExceptionsManagerConfig], 
    selector: "toast-alert", 
    templateUrl: "app/elements/components/construction/toast-alert/toast-alert.html", 
}) 
export class ToastComponent implements OnInit, OnDestroy { 
    ngOnInit(): void { 
     this.exceptionsManagerConfig.alertChangeEvent.subscribe(alert => this.showToast(alert)); 
     console.log("toast"); 
    } 

    ngOnDestroy(): void { 
    } 

    showToast = (alert: IAlert) => { 
     console.log(alert.message); 
    }; 

    constructor(private exceptionsManagerConfig: ExceptionsManagerConfig) { 

     this.exceptionsManagerConfig.alertChangeEvent.subscribe(alert => this.showToast(alert)); 
    } 
} 

corse我已经在主引导文件中设置了服务。

也许你有一些提示给我如何解决我的问题?

EventEmitter不应该用于服务。改为使用ObservableSubject@Output()在服务中是没有意义的。 @Output()仅在指令和组件中受支持。

无论如何,你的代码应该做你期望的。 我假设目前的问题是您在多个地方提供ExceptionsManagerConfig,导致一个组件在ExceptionManagerConfig的不同实例上调用ExceptionManagerConfig.setAlert(),然后将其注入到ToastComponent

您应该提供ExceptionManagerConfigNgModule(如果您使用≥= RC.5)或AppComponent来获得相同的实例注入到处。