기본 콘텐츠로 건너뛰기

Angular Http Interceptor 사용하기

Angular Http Interceptor 사용하기

Angular Http Interceptor 사용하기

이번 주제는 Angular 에서 전역으로 Api 요청을 컨트롤 하는 Http Intercepror 사용입니다.

주로 AuthToken을 사용한 Api 요청이나 전역적으로 Http 에러를 처리할 때 자주 쓰입니다.

Angular v8.1.2

먼저 새 프로젝트를 만들고 서비스를 만들어야겠죠.

// * src/services/example.service import { Injectable } from "@angular/core"; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ExampleService { private GOOGLE_API = 'https://www.googleapis.com/books/v1/volumes'; constructor( private http: HttpClient ) { } getBookList(): Observable { return this.http.get(`${this.GOOGLE_API}?orderBy=newest&q;=korean`) .pipe(map((books: any) => books.items || [])); } getBookListError(): Observable { return this.http.get(`${this.GOOGLE_API}?eerroorr`); } }

간단하게 Google Book Search API를 이용하는 서비스를 만들었습니다.

getBookList()는 정상적으로 API를 호출하고

getBookListError()는 의도적으로 error를 던지도록 만들었습니다.

그리고 AppComponent에 간단하게 해당 API를 호출하는 부분을 만들고,

// * src/app/app.component.ts import { Component } from '@angular/core'; import { ExampleService } from 'src/services/example.service'; import { take } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { successData$: Observable;; constructor(private service: ExampleService) { } getBook() { this.successData$ = this.service.getBookList(); } getError() { this.service.getBookListError().pipe(take(1)).subscribe(); } }

TEST HTTP INTERCEPTOR GET DATA THROW ERROR SUCESS DATA: {{item.id}}

/* src/app/app.component.css */ .main-wrap { display: flex; justify-content: center; align-items: center; height: 100%; } .box { width: 400px; min-height: 250px; padding: 20px; border-radius: 10px; box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); } .btn-wrap { display: flex; font-size: 1.6em; flex-direction: row; } .box .btn-wrap button{ width: 100%; padding: 10px; }

그냥 만들면 심심하니 약간의 스타일도 줍니다.

Home 화면

깔끔하게 나왔네요.

여기서 GET DATA 버튼을 클릭해서 데이터가 정상적으로 들어오는지 확인해봅시다.

GET DATA 실행

Book ID들이 정상적으로 successData에 들어옵니다.

이제 Throw Error를 실행시켜 볼까요?

THROW ERROR 실행

에러 메시지가 Alert으로 나타납니다.

여기서 위 코드를 보면 Error 처리한 부분이 없는데 어떻게 된 걸까요?

이 부분이 이번 예제에서 HttpInterceptor를 이용한 부분이죠.

HttpInterceptor 서비스를 살펴볼까요?

// app/src/services/http.interceptor.service.ts import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class HttpInterceptorService implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler): Observable> { let request: HttpRequest = req.clone(); return next.handle(request).pipe( catchError(e => { /** * 여기서 Error 원하는 방식으로 에러를 처리하자 */ alert(e.error.error.message); return throwError(e); }) ) } }

HttpInterceptor를 만들기 위해 먼저 HttpInterceptor 인터페이스를 구현해야 합니다.

intercept 함수를 구현해야 하는데 여기서 req 파라미터를 받습니다.

http 요청이 들어오면 intercept 함수에 해당 http request 가 들어오게 됩니다. 당연히 원래 request는 변경할 수 없기 때문에

req.clone()을 이용하여 기존 request를 복사합니다.

그리고 HttpHandler 형식인 next는 해당 req를 다음 행동으로 넘기는 역활을 합니다.

여기서는 req 를 가지고 http 요청을 직접 실행하는 부분이 되겠죠.

위 코드에서 next.handle 에 catchError operator를 붙여 (handle 역시 HttpEvent 타입의 Observable을 리턴합니다.)

http 요청에 에러가 난다면 해당 에러를 처리하도록 구성되어있고, 현재 alert으로 error 메시지를 나타내도록 되어있습니다.

만약 에러가 없다면 해당 catchError는 발생하지 않겠죠.

마지막으로 만들어진 http interceptor 서비스를 AppModule에 주입시킵시다.

// src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpInterceptorService } from '../services/http-interceptor.service'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, CommonModule, HttpClientModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }, ], bootstrap: [AppComponent] }) export class AppModule { }

이렇게 AppModule에 주입했습니다.

주입할 서비스의 token 이름은 HTTP_INTERCEPTORS라는 Angular에서 제공하는 토큰을 사용하고

사용할 class는 방금 만든 HttpInterceptorService를 사용하고, 전역적으로 제공하기 위해 multi 옵션은 true로 주었습니다.

이렇게 하면 전역적으로 http 요청에 관한 에러는 interceptor에서 처리하게 되었습니다.

추가로 인증 토큰을 http 요청 때마다 넣도록 만들어 볼까요? 간단합니다.

HttpInterceptorService에서 next로 넘기기 전에 request 객체에 header를 추가해주면 됩니다.

추가해봅시다.

// app/src/services/http-interceptor.service.ts import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; // 임시 토큰 function getToken() { return 'this is token'; } @Injectable() export class HttpInterceptorService implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler): Observable> { let request: HttpRequest; request = req.clone({ setHeaders: { Authorization: `Bearer ${getToken()}` } }); return next.handle(request).pipe( catchError(e => { /** * 여기서 Error 원하는 방식으로 에러를 처리하자 */ alert(e.error.error.message); return throwError(e); }) ) } }

원본 req를 복사하여 Authorization 헤더를 설정했습니다.

getToken() 같은 경우 임시로 만든 함수이며, 실제로는 Token Service를 만들어 관리하고 가져와야겠죠?

이런 식으로 하면

Http Interceptor

이제 모든 http 요청에 해당 header를 추가하여 요청하게 됩니다.

이렇게 Http Interceptor를 이용하여 전역적으로 http 요청하는 방법을 봤습니다.

글에 잘못된 점이 있다면 언제든 말해주세요.

Full Source Code : https://github.com/SiWonRyu/angular-httpInterceptor

from http://alexband.tistory.com/54 by ccl(A)

댓글

이 블로그의 인기 게시물

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증...

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증... django 는 기능이 참 너무 많다 ^^; 지금은 서버는 django로, 프론트는 angular를 붙여서 간단한 웹을 만들어 보려고 한다. 웹 만들때 항상 회원가입/로그인 기능은 맨 앞에 구현한다. 어떻게 구현하면 좋을까... 찾아보다가 이 기능을 구현할 수 있는 방법이 너무 많아서 정보를 찾기 더 어려웠다. 일단 나는 django에서 django rest framework라는 것을 사용해서 API를 만드려고 한다. 순수 django 튜토리얼에는 바로 template 랑 연결해서 설명하는 부분이 많았다. 나는 그냥 API 만 만들고 싶다고!! 그래서 찾은 것이 django REST framework. https://www.django-rest-framework.org/api-guide/authentication django REST framework 설치 using pip pip install djangorestframework settings.py INSTALLED APPS 에 추가해야함 INSTALLED_APPS = [ ... 'rest_framework', ] django REST framework 에서도 인증 관련해서 제공하는 것이 1개가 아닌 여러 개다. 나는 그중에 TokenAuthentication을 이용해서 로그인을 구현해 보려고 한다. TokenAuthentication Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. 이렇게 나와있어서 내가 하려는 것과 일치해서 이걸로 결정 ~ 솔직히 처음 로그인을 구현하려고 하면 도대체 그 과정이 어떻게 되는지 모를 수 도 있다. 나는 쉽게 정리하면 아래와 같은 과정이라고 생각한다. 로그인 로그아웃...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자... Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 팀 내 뛰어난 풀스택 개발자분들이 Angular.js, Python, MySQL 모두 작업 가능하시니 오셔서 함께 배우며 즐겁게 작업하시면 됩니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. 개발 업무: 레터플라이의 핵심 기능인 편지, 사진을 제작하는 레터에디터, 포토에디터 개발. 이 기능들은 "모바일 웹을 통한 출력제품 생산 자동화 기술"(특허 출원 준비중)로서 레터플라이에서 자체개발했습니다. 근무 지역: 광화문역 5번출구 바로 앞 근무 환경: 책임과 존중을 중요시하는 수평적인 분위기, 도전적이며 서로에게 배우는 문화 근무 시간: 10-19시, 출근시간 자유 지정. 급여: 연봉/스톡옵션 협의 지원 방법: 팀 지원하기 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/721 by ccl(A) rewrite - 2020-03-20 09:20:18

jqxGrid 정렬, 필터 메뉴 숨기기

jqxGrid 정렬, 필터 메뉴 숨기기 How I can remove filter to particular grid column - Angular, Vue, React, Web Components, Javascript, HTML5 Widgets Hi, I tried that it's working. I set properties to those columns as sortable: false, filterable: false. but when I clicked on the column one drop down is appearing with options "sort ascending", "sort descending", "remove sort" and those are all in disable www.jqwidgets.com from http://devesim.tistory.com/90 by ccl(A) rewrite - 2020-03-11 04:20:29