How do I use an Angular service in my custom rxjs operator?
Is it possible to do this?
function myOperator() {
return function <T>(source: Observable<T>): Observable<T> {
return new Observable(subscriber => {
const subscription = source.subscribe({
next(value) {
//access an Angular service HERE
subscriber.next(value);
},
error(error) {
subscriber.error(error);
},
complete() {
subscriber.complete();
}
});
return () => subscription.unsubscribe();
});
};
}
I'd like to use it in an observable pipe:
observable
.pipe(
myOperator()
)
.subscribe(result => {
});
Creating and registering an injector, bootstrapping it and using it in the custom operator seems to work well, without having to use a service.
This can be registered during the bootstrapping:
And then be used in the custom operator:
This causes tests to crash because RootInjector is not set up. But placing this in root-injector.mock.ts file:
..and then importing it into the jasmine test file did the trick:
Note that this only works for services providedIn: 'root'
Thanks to this post!: https://nartc.netlify.app/blogs/root-injector/