voliva / angular2-interceptors

79 stars 20 forks source link

Injecting into ServerURLInterceptor #9

Open IonPopescu opened 7 years ago

IonPopescu commented 7 years ago

I am converting an Angular 1 application, and I have some existing authentication-related functionality that I'd like to reuse:

export function Auth ($rootScope, $q: ng.IQService, $injector, $window: ng.IWindowService) {
    // auth functionality is here...
}

Auth.$inject = [
    "$rootScope", "$q", "$injector", "$window"
];

In the provided example, would it be possible to inject the Auth function above into ServerUrlInterceptor?

providers: [
        {
            provide: InterceptorService,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => {
                let service = new InterceptorService(xhrBackend, requestOptions);
                service.addInterceptor(new ServerURLInterceptor(/* TODO: inject Auth here (??) */)); 
                return service;
            },
            deps: [XHRBackend, RequestOptions]
        }
    ]

Thank you

voliva commented 7 years ago

I think you need to create an Interceptor that handles your Auth. ServerURLInterceptor is just an example where it will append the serverURL to each one of the calls. It also looks like you need to inject other services/dependencies, so your Interceptor has to be a service as well.

For instance, normally, for Auth interceptors you want to get all the requests that are about to go to the server and add a header to them. You should then create your interceptor:

export class AuthInterceptor implements Interceptor {
    constructor(
        // services to be injected here
    ) { }

    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
        // Any logic you want for this request
        request.options.headers.append("Authorization", "your-token-here");

        return request;
    }
}

And then add it like so:

providers: [
        AuthInterceptor, // You need to add it in the provider list, so it can be injected
        {
            provide: InterceptorService,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, authInterceptor: AuthInterceptor) => {
                let service = new InterceptorService(xhrBackend, requestOptions);
                service.addInterceptor(authInterceptor); 
                return service;
            },
            deps: [XHRBackend, RequestOptions, AuthInterceptor] // Here you inject it into the useFactory function above
        }
    ]

I will have to rewrite the documentation to make these things more clear + add some examples.

crissi commented 7 years ago

+1 on documention on using other services inside the "ServerUrlInterceptor"