Reputation: 2222
I have a service:
import { EventEmitter, Injectable } from '@angular/core';
@Injectable()
export class PingOnActionListenerService {
removingListener = new EventEmitter();
removeListener(): void {
this.removingListener.emit();
}
At component A I call the service:
this._pingOnActionListenerService.removeListener();
At component B I want to listen to the service:
ngOnInit() {
this._pingOnActionListenerService.removingListener.subscribe(this.deactivatelistener());
}
deactivatelistener() {
window.removeEventListener('click', this.pingIfLastPingIsOld);
}
When I run this code, I get at the console the error message:
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) at PingOnActionListenerService.push../src/app/core/services/ping-on-action/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)
Upvotes: 3
Views: 8347
Reputation: 9591
While not directly relevant to the OP's question, I'm posting this in case it helps others.
The error generatorOrNext is not a function
, can be caused by doing something similar to the below, where there is no callback passed to .subscribe().
this.subject.valueChanges.subscribe(
// (newVal) => console.log(newVal)
);
Upvotes: 5
Reputation: 4039
You should not use EventEmitter
in Service, that is supposed to be used for component bindings and @Output()
only. You should redesign that as Subject/Observable
:
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));
}
}
And in component B use:
ngOnInit() {
this._pingOnActionListenerService.removeListener$
.subscribe(() => {
this.deactivatelistener();
});
}
Don't forget to unsubscribe in component ngOnDestroy
.
Upvotes: 2