Skip to content

Instantly share code, notes, and snippets.

@mitsuruog
Last active August 16, 2016 02:55
Show Gist options
  • Save mitsuruog/6f7f0ca3f546b245bccdd3ebc14375d8 to your computer and use it in GitHub Desktop.
Save mitsuruog/6f7f0ca3f546b245bccdd3ebc14375d8 to your computer and use it in GitHub Desktop.
Angular2でHttpInterceptorが欲しいお

Angular2 HttpInterceptor Needed

Who am I

HttpInterceptorとは

  • XHRに関連する横断的機能(cross-cutting)を分離する
    • Global Error handling
    • Fail back to show notification
  • Angular1ではHttpInterceptorを使うことで、これらを綺麗に分離できた

How about a httpInterceptor in Angular 2 ?

結論

簡単にできない!!

Way of httpInterceptor in Angular 2

following step

  1. 既存のHttpをOverrideするためのCustomHttpサービスを作成する
  2. bootstrapで既存のHttpをOverideする

⚠️

Create a CustomHttp service

custom-http.service.ts

import {Http, ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response} from "angular2/http";
import {Observable} from "rxjs/Observable";

export class CustomHttp extends Http {

    constructor(backend:ConnectionBackend,
                defaultOptions:RequestOptions) {
        super(backend, defaultOptions)
    }

    request(url:string | Request, options?:RequestOptionsArgs):Observable<Response> {
        return super.request(url, options).catch(this.handleResponseError);
    }

    get(url:string, options?:RequestOptionsArgs):Observable<Response> {
        return super.get(url, options).catch(this.handleResponseError);
    }

    // ...
    
    private handleResponseError(res:Response) {
        if (res.status === 401) {
          // do something
        } else if (res.status === 500) {
          // do something
        }
        return Observable.throw(res);
    }
}

Override Http to CustomHttp at bootstrap

main.ts

import 'rxjs/Rx';

import {bootstrap} from 'angular2/platform/browser';
import {Provider} from "angular2/core";

import {AppComponent} from './app.component';
import {CustomHttp} from "./common/services/custom-http.service";

bootstrap(AppComponent, [
    new Provider(Http, {
        useFactory: (backend:XHRBackend, defaultOptions:RequestOptions) => {
            return new CustomHttp(backend, defaultOptions)
        },
        deps: [XHRBackend, RequestOptions]
    })
]);

Conclusion

  • Angualr2でもAngular1のHttpInterceptorと近いことはできる。
  • ただ、少し面倒だ。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment