在我的angular2-Application内的SignalR-Service中,当我从服务器收到一个事件时,我想广播一个事件。
@Injectable() export class SignalRService {
//...
private emitMe: EventEmitter<any>;
constructor() {
this.emitMe = new EventEmitter();
this.connection = jQuery.hubConnection(".../signalr/");
this.proxy = this.connection.createHubProxy("...");
this.wireupEvents();
//...
}
wireupEvents(): void {
this.proxy.on('ItemAdded', function(data) {
console.log('received ItemAdded' + JSON.stringify(data));
//How to throw event here??? Like $rootScope.$emit('itemAdded', data);
// 'this.emitMe' is not reachable here
});
}
}我如何访问我初始化的EventEmitter并抛出一个我可以从外部订阅的事件?
谢谢
关于Tenoda
发布于 2016-01-18 23:19:50
你可以试着这样做:
constructor() {
this.emitMe = new EventEmitter();
//...
}
wireupEvents(): void {
this.proxy.on('ItemAdded', (data) => {
console.log('received ItemAdded' + JSON.stringify(data));
let someObject = (...)
this.emitMe.emit(someObject);
});
}使用箭头函数,您可以直接在回调中使用this关键字。这个答案也可以帮助你:Angular 2 can't call class function。
希望对你有帮助,蒂埃里
发布于 2017-07-11 22:30:21
只需将这个赋值给那个并使用它,
private emitMe: EventEmitter<any> = new EventEmitter();
wireupEvents(): void {
let that = this;
this.proxy.on('ItemAdded', function(data) {
console.log('received ItemAdded' + JSON.stringify(data));
that.emitMe.emit(data);
});
}疯狂的权利;)。this的变量作用域不是您需要的this,因此this没有emit,但是通过将this赋值给that,现在我们就有了emit
https://stackoverflow.com/questions/34857124
复制相似问题