티스토리 뷰

FrontEnd/Angular

Angular HTTP 인터셉터

철철22 2018. 8. 22. 10:11
반응형

Angular 4.3부터 추가된 HttpClientModule에는 http 요청에 인터셉터를 적용할 수 있다.


인터셉터를 간단히 설명하면 api나 특정 data를 요청 할 때 그 요청을 가로채는 역할을 한다.


인터셉터를 사용하기 위해서는 HttpInterceptor를 구현해야 한다.


interface HttpInterceptor {
  // intercept의 첫번째 인자는 처리할 요청을 받고, 두번째는 다음 인터셉터를 가리키는 HTTP 핸들러다.
  intercept(req: HttpRequest, next: HttpHandler): Observable<httpevent<any>>
}


ex) 서버에서 보내준 헤더 받기



export class HeaderInterceptor implements HttpInterceptor {

	intercept(req: HttpRequest<any>, next: HttpHandler): Observable<httpevent<any>> {

		const token = localStorage.getItem('token');
		let newHeader: HttpHeaders = req.headers;
		
                if (token) {
			newHeader = newHeader.set('X-Auth-Token', token);
		}
                // intercept의 req는 이뮤터블(인스턴스의 내용이 변하지 않는다 <-> 뮤터블)이다.
                // 헤더를 추가하거나 변경을 하려면 clone 함수를 통해 새로운 httpRequest객체를 생성해야 한다.
		const clonedRequest = req.clone({headers: newHeader});

                // next.handle 로부터 인터셉터를 체이닝(엮다, 묶다)한다.
		return next.handle(clonedRequest); 
	}
}

// 모듈 추가
@NgModule({
	imports: [
		HttpClientModule,
	],
	providers: [
		LoaderService,
		{
			provide: HTTP_INTERCEPTORS, // InjectionToken
			useClass: HeaderInterceptor,

                        // HTTP_INTERCEPTORS가 단일 값이 아닌 배열을 주입한는 multiprovider에 대한 토큰임을 설정한다(영알못 해석)
			multi: true,
		}
	],
})
export class CoreModule {

}


이런식으로 헤더에 대한 정보를 얻기위해 인터셉터를 사용할 수도 있고,


spa에서 reatAPI를 통해 데이터를 받을 때 로딩표시를 표현하기 위해 사용할 수도 있고 다양하게 사용할 수 있다.



그리고 인터셉터는 컴포넌트의 변경때마다 호출이 되는데 

필요할 때만 호출을 할 수 있는 방법이 있을 꺼 같다. 나중에 한번 찾아봐야겠다.



참고 : http://han41858.tistory.com/39

https://angular.io/guide/http#intercepting-requests-and-responses

반응형

'FrontEnd > Angular' 카테고리의 다른 글

2018-09-10 개발일지  (0) 2018.09.11
ng-template 와 ng-container  (0) 2018.08.30
Angular Data Chart 추천  (0) 2018.08.20
Angular Server Side Rendering  (0) 2018.08.13
angular 파일업로드  (0) 2018.08.08
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함