从HttpInterceptor中调用组件的函数?
问题描述:
是否可以从HttpInterceptor
调用组件中的函数?从HttpInterceptor中调用组件的函数?
@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {
// constructor(@Inject(DOCUMENT) private document: any) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('HttpRequest<any> called');
const started = Date.now();
// Call component function
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// Call component function on response
}
});
}
}
答
您无法从服务调用组件中的函数。这不是Angular的工作原理。如果你想这样做,你必须将该组件的类实例传递给服务,并且它必须具有可公开访问的属性。但这是一个肮脏的方法,你应该避免它。
但是,您可以添加到服务的可观察流中,并且组件可以订阅该可观察流并调用它想要的任何函数。这将是这样做的“角度方式”。
使用这种方法,您可以根据需要在任意数量的组件中获得相同的数据片段,并且可以在这些组件中调用尽可能多的功能。你只需要拨打subscribe()
即可。
例如:
@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) {
// Pass in some data in the `next()` function.
// Every time this is called, your components subscription function will be triggered.
this.dataStream.next(...);
}
});
}
}
@Component({...})
export class MyComponent {
ngOnInit() {
this.httpInterceptorService.dataStream$().subscribe(data => {
// This will be triggered every time data is added to the stream in your HttpInterceptorService class.
// Call your custom function here...
});
}
}
如果你想重用的功能,请尝试设置功能在服务 –
我不知道,但好主意是whorte的机能的研究服务和共享在拦截器和组件,如果可能。 –