반응형
Angular 애플리케이션에 여러 HTTP 인터셉터 추가
Angular 4 애플리케이션에 여러 개의 독립적 인 HTTP 인터셉터를 추가하는 방법은 무엇입니까?
providers
하나 이상의 인터셉터로 배열을 확장하여 추가하려고했습니다 . 그러나 마지막 하나만 실제로 실행되고 Interceptor1
무시됩니다.
@NgModule({
declarations: [ /* ... */ ],
imports: [ /* ... */ HttpModule ],
providers: [
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
new Interceptor1(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions],
},
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
new Interceptor2(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions]
},
],
bootstrap: [AppComponent]
})
export class AppModule {}
분명히 그것들을 단일 Interceptor
클래스 로 결합 할 수 있으며 작동합니다. 그러나이 인터셉터는 완전히 다른 목적을 가지고 있기 때문에 피하고 싶습니다 (하나는 오류 처리 용, 하나는 로딩 표시기를 표시하기위한 것).
그렇다면 여러 인터셉터를 어떻게 추가 할 수 있습니까?
Http
둘 이상의 사용자 정의 구현을 허용하지 않습니다. 그러나 @estus가 언급했듯이 Angular 팀은 최근 여러 인터셉터 개념을 지원 하는 새로운 HttpClient 서비스 (릴리스 4.3)를 추가했습니다 . HttpClient
이전 .NET과 마찬가지로 확장 할 필요가 없습니다 Http
. HTTP_INTERCEPTORS
대신 다음 'multi: true'
옵션을 사용 하여 배열이 될 수 있는 구현을 제공 할 수 있습니다 .
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
...
@NgModule({
...
imports: [
... ,
HttpClientModule
],
providers: [
... ,
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorOne,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorTwo,
multi: true,
}
],
...
})
인터셉터 :
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
...
@Injectable()
export class InterceptorOne implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('InterceptorOne is working');
return next.handle(req);
}
}
@Injectable()
export class InterceptorTwo implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('InterceptorTwo is working');
return next.handle(req);
}
}
이 서버 호출은 두 인터셉터의 로그 메시지를 인쇄합니다.
import {HttpClient} from '@angular/common/http';
...
@Component({ ... })
export class SomeComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('http://some_url').subscribe();
}
}
참고 URL : https://stackoverflow.com/questions/45633102/add-multiple-http-interceptors-to-angular-application
반응형
'Program Tip' 카테고리의 다른 글
Genymotion이 Android 가상 장치를 시작하지 않습니다. (0) | 2020.11.20 |
---|---|
다중 처리 : tqdm을 사용하여 진행률 표시 줄 표시 (0) | 2020.11.20 |
onClick 핸들러 내의 JavaScript 코드 내에서 문자열을 어떻게 이스케이프합니까? (0) | 2020.11.20 |
WHERE 절에서 별칭 사용 (0) | 2020.11.20 |
Wix에서 이전에 설치된 프로그램 버전을 업데이트하는 방법 (0) | 2020.11.20 |