Avoid calling a component method from a service as it is not considered best practice. Instead of passing the class instance of that component into the service, which requires publicly accessible properties, opt for a cleaner approach.
One recommended alternative is to add to an observable stream from a service and allow components to subscribe to this stream, enabling them to call desired functions. This follows "the Angular way" of handling such situations.
By using this method, you can retrieve the same data across multiple components and execute various functions within those components. Simply utilize the subscribe()
function.
For example:
@Injectable()
export class HttpResponseInterceptor {
dataStream: ReplaySubject<any> = new ReplaySubject();
dataStream$(): Observable<any> {
return this.dataStream().asObservable();
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('HttpRequest<any> called');
const started = Date.now();
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// Include data in the `next()` function.
// Any subscription function in your components will be triggered upon each call.
this.dataStream.next(...);
}
});
}
}
@Component({...})
export class MyComponent {
ngOnInit() {
this.httpInterceptorService.dataStream$().subscribe(data => {
// Triggered whenever new data is added to the stream in your HttpInterceptorService class.
// Implement any necessary custom functionality here...
});
}
}