[Angular] HTTPInterceptor 를 이용하여 파일 업로드 중지하기

안녕하세요. 명동섞어찌개입니다.
오늘은 Angular 에서 파일 업로드 기능 개발 시, 원하는 시점에 파일 업로드를 중지하는 기능에 대해 알아보도록 하겠습니다.

요점은 페이지 이동이나 파일 업로드 취소 버튼을 누르는 순간, HTTPIntercepter 를 이용하여 서버에 보내는 요청을 취소하여 파일 업로드를 중지하는 기능을 만드는 겁니다!


1. HttpCancelService 를 만듭니다

실질적으로 http 요청을 취소하는 부분입니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable()
export class HttpCancelService {

    private pendingHTTPRequests = new Subject<void>();

    constructor() {
    }

    public cancelPendingRequests() {
        this.pendingHTTPRequests.next();
    }

    public onCancelPendingRequests() {
        return this.pendingHTTPRequests.asObservable();
    }
}



2. 공통으로 어느 페이지에서나 호출하기 위해서 이벤트를 설정해 줍니다.

이거는 만드는 방식의 차이인데요
저는 어느 페이지에서나 접근 가능한 공통 commonCode 에 페이지 공통으로 쓸 이벤트를 하나 정의해 두었습니다. (이벤트를 쓰는 건 간편하긴 하지만 남발할 경우 ...... 권장하지는 않습니다. 프로젝트 상황에 맞게 쓰세요!)

1
export const COMMON_EVENT = new EventEmitter();



3. HTTPIntercepter 를 만듭니다

위에서 만든 공통 이벤트를 통해 'stop_file_upload' 라는 요청을 보내면 이 Interceptor 가 듣고, httpCancelService 의 함수를 호출해서 http 통신을 취소하게 됩니다.

 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
import {Injectable} from '@angular/core';
import {ActivationEnd, Router} from '@angular/router';
import {HttpCancelService} from '../http-cancel.service';
import {HttpEvent, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import * as commonCode from '../../../shared/config/commonCode';

@Injectable()
export class ManageHttpInterceptor {

    CODE = commonCode;

    constructor(
        router: Router,
        private httpCancelService: HttpCancelService
    ) {
        this.CODE.COMMON_EVENT.subscribe( e => {
            if(e == 'stop_file_upload') {
                this.httpCancelService.cancelPendingRequests();
            }
        });
    }

    intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return next.handle(req).pipe(takeUntil(this.httpCancelService.onCancelPendingRequests()));
    }
}



4. core.module 에 (1) HttpCancelService 와 (3) HTTPIntercepter 를 세팅합니다

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {HttpCancelService} from './services/http-cancel.service';
import {ManageHttpInterceptor} from './services/interceptor/manage-http.interceptor';

@NgModule({
    imports: [
        HttpClientModule,
    ],
    providers : [
        HttpCancelService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: ManageHttpInterceptor,
            multi: true
        },
    ]
})
export class CoreModule {
}



5. 마지막으로 파일 업로드를 하는 화면에서, 업로드 중지 요청을 보내는 함수를 만듭니다.


1
2
3
4
import * as commonCode from '../../../shared/config/commonCode';

.
.

CODE = commonCode;

.
.

public stopFileUploading() {
        //파일업로드중지
        this.CODE.COMMON_EVENT.emit('stop_file_upload');
    }

이제 언제 어디서든 파일 업로드를 중지해야 하는 상황이 생기면 위와 같이 호출해주시면 됩니다.

(업로드 취소 버튼을 누르거나, 브라우저에서 뒤로 가기를 누르는 등 - Angular 에서 브라우저 뒤로 가기를 눌렀을 때 처리방법 글 참조 )











댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

SPA(Sigle Page Applications) 란 무엇인가?

안드로이드에서 당겨서 새로고침(SwipeRefreshLayout) 쉽게 구현하기

[AWS] WinSCP 를 이용해 Linux 인스턴스로 파일 전송하기