2017-08-24 65 views
2

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

} 
+0

如果你想重用的功能,請嘗試設置功能在服務 –

+0

我不知道,但好主意是whorte的機能的研究服務和共享在攔截器和組件,如果可能。 –

回答

1

您無法從服務調用組件中的函數。這不是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... 
     }); 
    } 
}