我有一个服务:
import { EventEmitter, Injectable } from '@angular/core';
@Injectable()
export class PingOnActionListenerService {
removingListener = new EventEmitter();
removeListener(): void {
this.removingListener.emit();
}
在组件A中,我调用了该服务:
this._pingOnActionListenerService.removeListener();
在组件 B 中,我希望监听该服务:
ngOnInit() {
this._pingOnActionListenerService.removingListener.subscribe(this.deactivatelistener());
}
deactivatelistener() {
window.removeEventListener('click', this.pingIfLastPingIsOld);
}
当我运行这段代码时,在控制台上会有一个错误信息:
core.js:1671 ERROR TypeError: generatorOrNext is not a function at SafeSubscriber.schedulerFn [as _next] (core.js:3565) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:133) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at EventEmitter.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next (Subject.js:47) at EventEmitter.push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit (core.js:3537) 在ping-on-action-listener.service.ts.PingOnActionListenerService.removeListener (ping-on-action-listener.service.ts:19) at CatchSubscriber.selector (logging-interceptor.ts:45) at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:33)
this.deactivatelistener()
返回未定义,因此您正在将undefined
传递给订阅。 - user184994this._pingOnActionListenerService.removingListener.subscribe(this.deactivatelistener());
这里你没有调用removingListener
函数。 - callbackremovingListener
不是一个函数,而是一个EventEmitter
。 - user184994subscribe(this.deactivatelistener());
中,应该改为subscribe(this.deactivatelistener)
或subscribe(() => this.deactivatelistener())
。 - callbacksomeFn(this.cb)
的行为不如预期。如果this.cb
在某种方式上引用了this
,那么它将不是你所说的this.cb
所在的相同的this
。它将是最终调用回调函数的作用域。如果this.cb
引用了this
,请使用第二个选项。 - RoboticRenaissance