从HttpInterceptor调用Component中的函数?

时间:2017-08-24 16:17:43

标签: angular typescript angular-components

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

}

1 个答案:

答案 0 :(得分:2)

您无法从服务中调用组件中的函数。这不是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...
        });
    }
}