Angular 2
HTTP 인터셉터
수색…
비고
HttpServiceLayer 클래스로 수행하는 작업은 Http 클래스를 각도에서 확장하고 자체 로직을 추가하는 것입니다.
그런 다음 해당 클래스를 응용 프로그램의 부트 스트랩 클래스에 삽입하고 HttpServiceLayer를 삽입하기 위해 Http 클래스를 가져온 각도를 알려줍니다.
코드의 어디에서나 간단하게 가져올 수 있습니다.
import { Http } from '@angular/http';
그러나 우리 수업은 매 통화마다 사용됩니다.
단순 클래스 확장 각도의 Http 클래스
import { Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/empty';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import { ApplicationConfiguration } from '../application-configuration/application-configuration';
/**
* This class extends the Http class from angular and adds automaticaly the server URL(if in development mode) and 2 headers by default:
* Headers added: 'Content-Type' and 'X-AUTH-TOKEN'.
* 'Content-Type' can be set in any othe service, and if set, it will NOT be overwritten in this class any more.
*/
export class HttpServiceLayer extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router, private appConfig: ApplicationConfiguration) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
this.getRequestOptionArgs(options);
return this.intercept(super.request(this.appConfig.getServerAdress() + url, options));
}
/**
* This method checks if there are any headers added and if not created the headers map and ads 'Content-Type' and 'X-AUTH-TOKEN'
* 'Content-Type' is not overwritten if it is allready available in the headers map
*/
getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
if (!options.headers.get('Content-Type')) {
options.headers.append('Content-Type', 'application/json');
}
if (this.appConfig.getAuthToken() != null) {
options.headers.append('X-AUTH-TOKEN', this.appConfig.getAuthToken());
}
return options;
}
/**
* This method as the name sugests intercepts the request and checks if there are any errors.
* If an error is present it will be checked what error there is and if it is a general one then it will be handled here, otherwise, will be
* thrown up in the service layers
*/
intercept(observable: Observable<Response>): Observable<Response> {
// return observable;
return observable.catch((err, source) => {
if (err.status == 401) {
this._router.navigate(['/login']);
//return observable;
return Observable.empty();
} else {
//return observable;
return Observable.throw(err);
}
});
}
}
Angular 's Http 대신에 클래스 사용하기
Http 클래스를 확장 한 후에는 Http 클래스 대신이 클래스를 사용하도록 각도를 지정해야합니다.
이렇게하기 위해서, 우리의 메인 모듈 (또는 필요에 따라, 특정 모듈)에, 우리는 제공자 섹션에 다음을 써야합니다 :
export function httpServiceFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) {
return new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig);
}
import { HttpModule, Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { Router } from '@angular/router';
@NgModule({
declarations: [ ... ],
imports: [ ... ],
exports: [ ... ],
providers: [
ApplicationConfiguration,
{
provide: Http,
useFactory: httpServiceFactory,
deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
참고 : ApplicationConfiguration은 응용 프로그램 기간 동안 일부 값을 보유하는 데 사용하는 서비스 일뿐입니다.
간단한 HttpClient AuthToken 인터셉터 (각도 4.3 이상)
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { UserService } from '../services/user.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthHeaderInterceptor implements HttpInterceptor {
constructor(private userService: UserService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.userService.isAuthenticated()) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${this.userService.token}`
}
});
}
return next.handle(req);
}
}
인터셉터 제공 (some-module.module.ts)
{provide: HTTP_INTERCEPTORS, useClass: AuthHeaderInterceptor, multi: true},
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow