【发布时间】:2016-05-16 16:25:32
【问题描述】:
我在我的 angular2 服务中使用 EventEmitter 触发一个事件。但是这个事件并没有被我的组件捕获。
我的服务(文件是 - 'app.service.ts'):
import {EventEmitter, Injectable, OnInit} from "angular2/core";
@Injectable()
export class AppService{
private _event:EventEmitter<string> = new EventEmitter();
ngOnInit(){
setTimeout(() => this._event.emit("hello"),1000);
}
getEventRef(){
return this._event;
}
}
我的组件(文件是'./app.component.ts'):
import {Component, OnInit} from "angular2/core";
import {AppService} from "./app.service";
@Component({
selector: 'my-app',
template: '<h1>App</h1>',
providers: [AppService]
})
export class AppComponent implements OnInit{
constructor(private _service:AppService){}
ngOnInit(){
_service.getEventRef()
.subscribe(res => alert(res));
}
}
但是我没有收到我应该在我的组件中获得的警报。我不确定该服务是否正在使用 .emit api 触发事件。
【问题讨论】: