gpt4 book ai didi

angular - 从 HttpInterceptor 调用组件中的函数?

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:46 25 4
gpt4 key购买 nike

是否可以从 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...
});
}
}

关于angular - 从 HttpInterceptor 调用组件中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45866574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com