我有服务:
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错误TypeError:generatorOrNext不是函数 在SafeSubscriber.schedulerFn [作为_next](core.js:3565) 在SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub(Subscriber.js:195) 在SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber.next(Subscriber.js:133) 在Subscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._next(Subscriber.js:77) 在Subscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next(Subscriber.js:54) 在EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Subject.js.Subject.next(Subject.js:47) 在EventEmitter.push ../ node_modules/@angular/core/fesm5/core.js.EventEmitter.emit(core.js:3537) 在 PingOnActionListenerService.push ../ src / app / core / services / ping-on-action / ping-on-action-listener.service.ts.PingOnActionListenerService.removeListener (ping-on-action- listener.service.ts:19) 位于CatchSubscriber.selector (logging-interceptor.ts:45) 在CatchSubscriber.push ../ node_modules / rxjs / _esm5 / internal / operators / catchError.js.CatchSubscriber.error(catchError.js:33)
答案 0 :(得分:3)
虽然与OP的问题不直接相关,但我会发布此消息以防其他人遇到问题。
错误generatorOrNext is not a function
可能是由于执行以下类似操作而导致的,其中没有将回调传递给.subscribe()。
this.subject.valueChanges.subscribe(
// (newVal) => console.log(newVal)
);
答案 1 :(得分:2)
您不应在Service中使用Disposables.create(myDisposable)
,而应该将EventEmitter
仅用于组件绑定。您应该将其重新设计为@Output()
:
Subject/Observable
在组件B中使用:
export class PingOnActionListenerService {
_removingListener = new BehaviorSubject<boolean>(false);
removeListener(): void {
this._removingListener.next(true);
}
get removeListener$(): Observable<boolean> {
return this._removingListener.asObservable()
.pipe(filter(val => val));
}
}
别忘了退订组件ngOnInit() {
this._pingOnActionListenerService.removeListener$
.subscribe(() => {
this.deactivatelistener();
});
}
。