Coder Social home page Coder Social logo

angular2-interceptors's Introduction

NG2-Interceptors

This package adds the interceptor feature to Angular 2, by extending the @angular/http class. For concept behind Interceptor, take a look at the wiki

Installation

To install, just run in your angular project:

npm install ng2-interceptors --save

And it should be importable with webpack out of the box

Usage

Set up InterceptorService

Interceptors are registered when the service is created (to avoid any race-condition). To do so, you have to provide the instance of the service by yourself. So on your module declaration, you should put a provider like:

import { InterceptorService } from 'ng2-interceptors';
import { XHRBackend, RequestOptions } from '@angular/http';

export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions){
  let service = new InterceptorService(xhrBackend, requestOptions);
  // Add interceptors here with service.addInterceptor(interceptor)
  return service;
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    {
      provide: InterceptorService,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [AppComponent]
})

There's a shorthand for this setup by using provideInterceptorService, but if you use AoT (Ahead-of-time) compilation it will fail. In fact, exporting the interceptorFactory is to make the AoT Compiler, as it needs all functions used in the provider to be exported.

import { provideInterceptorService } from 'ng2-interceptors';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    provideInterceptorService([
      // Add interceptors here, like "new ServerURLInterceptor()" or just "ServerURLInterceptor" if it has a provider
    ])
  ],
  bootstrap: [AppComponent]
})

Using InterceptorService

Once we have it set up, we can use it in our Controllers as if we were using the default Angular Http service:

import { Component } from '@angular/core';
import { InterceptorService } from 'ng2-interceptors';

@Component({
  selector: 'my-component',
  templateUrl: 'my-component.html',
  moduleId: 'my-module'
})
export class MyComponent {

  constructor(
     private http: InterceptorService) {
  }

  ngOnInit(){
    this.http.get("http://www.example.com/").subscribe(
      (res) => console.log(res),
      (err) => console.error(err),
      () => console.log("Yay"));
  }
}

We can also "cheat" the Injector so that every time we ask for the Http we get the InterceptorService instead. All we have to do is replace InterceptorService on the provider definition for Http, and then we can get our service when we use private http: Http:

  {
    provide: Http,
    useFactory: interceptorFactory,
    deps: [XHRBackend, RequestOptions]
  }

Creating your own Interceptor

Basically, an interceptor is represented by one pair of functions: One that will get the request that's about to be sent to the server, and another that will get the response that the server just sent. For that, we just need to create a new class that implements Interceptor:

import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';

export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
        // Do whatever with request: get info or edit it

        return request;
        /*
          You can return:
            - Request: The modified request
            - Nothing: For convenience: It's just like returning the request
            - <any>(Observable.throw("cancelled")): Cancels the request, interrupting it from the pipeline, and calling back 'interceptAfter' in backwards order of those interceptors that got called up to this point.
        */
    }

    public interceptAfter(response: InterceptedResponse): InterceptedResponse {
        // Do whatever with response: get info or edit it

        return response;
        /*
          You can return:
            - Response: The modified response
            - Nothing: For convenience: It's just like returning the response
        */
    }
}

Both methods are optional, so you can implement Interceptors that just take request or responses.

Notice how there's a different object of InterceptedRequest and InterceptedResponse: They are modifications of angular's Http Request and Response needed for the whole Interceptor feature and to pass additional options that may be needed for specific interceptors (like to enable/disable them for specific calls, etc.) the API is:

interface InterceptedRequest {
    url: string,
    options?: RequestOptionsArgs, // Angular's HTTP Request options
    interceptorOptions?: any
}
interface InterceptedResponse {
    response: Response, // Angular's HTTP Response
    interceptorOptions?: any
}

interceptorOptions on InterceptedRequest is guaranteed to be the same of that one of InterceptedResponse for the same call: The stuff you put in interceptorOptions while in interceptBefore will be available when you get interceptAfter called.

Creating one Injectable Interceptor

Interceptors are usually pure classes with pure functions: Given a call, they return a modified one, but sometimes we need these Interceptors to be actual Services to be used all around our application.

For instance, an interceptor that shows a loading spinner every time we have a call has -in some way- to comunicate with the LoadingComponent to make the spinner appear/disappear from the screen.

To do that you have to do some steps in the module/factory declaration file:

  1. Create a Service (@Injectable() annotation) that implements Interceptor and the interceptor methods.
  2. Define his provider before InterceptorService
  3. Add it as a parameter to the factory function
  4. Add it to the deps array. Note that the order of the elements have to match the one on the factory function.
  5. Add it to the pipeline

If you are using the provideInterceptorService option (without AoT Compiler support), then you can skip steps 2-4.

If our ServerURLInterceptor were a Service, we would have a module declaration like:

import { InterceptorService } from 'ng2-interceptors';
import { ServerURLInterceptor } from './services/serverURLInterceptor';
import { XHRBackend, RequestOptions } from '@angular/http';

export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, serverURLInterceptor:ServerURLInterceptor){ // Add it here
  let service = new InterceptorService(xhrBackend, requestOptions);
  service.addInterceptor(serverURLInterceptor); // Add it here
  return service;
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    ServerURLInterceptor, // Add it here
    {
      provide: InterceptorService,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerURLInterceptor] // Add it here, in the same order as the signature of interceptorFactory
    }
  ],
  bootstrap: [AppComponent]
})

angular2-interceptors's People

Contributors

andrewstuart avatar henriquecustodia avatar nsmgr8 avatar pafsec avatar voliva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular2-interceptors's Issues

interceptBefore not called

I am working on an app which is transpiled to es5 and there is something that I don't understand (sorry in advance if my question is stupid).

I created my own interceptor and I added to the the interceptor service :

export class TimeoutInterceptor implements Interceptor {

     private _timeout: number = 1;

     public interceptBefore(request: InterceptedRequest): Observable<InterceptedRequest> {
         return Observable.of<InterceptedRequest>(request)
             .timeout(this._timeout);
     }

     public interceptAfter(response: InterceptedResponse): InterceptedResponse {
         return response;
     }
 }

But in the interceptor-service.js file at the line 176 there is a test
if (!bf.interceptBefore)
and it returns undefined.

When I debug I see my interceptor in the list and I see in the prototype of it the correct function. If I debug bf.prototype.interceptBefore the function exists :

bf: TimeoutInterceptor()
   arguments:(...)
   caller:(...)
   length:0
   name:"TimeoutInterceptor"
   prototype:Object
       constructor:
       TimeoutInterceptor()
       interceptAfter:(response)
       interceptBefore:(request)
       __proto__:Object
   __proto__:()
   [[FunctionLocation]]:timeout.interceptor.ts:4
   [[Scopes]]:Scopes[2]

Thank you in advance

TypeError: Cannot read property 'interceptorOptions' of undefined

Happens as

TypeError: Cannot read property 'interceptorOptions' of undefined
    at InterceptorService.request (x\node_modules\ng2-interceptors\lib\interceptor-service.js:94:44)
    at AuthHttp.requestWithToken (\x\node_modules\angular2-jwt\angular2-jwt.js:109:26)
    at MergeMapSubscriber.eval [as project] (x\node_modules\angular2-jwt\angular2-jwt.js:133:107)

angular2-jwt uses Http that is currently provided by ng2-interceptor. However seemingly it passes an undefined options argument that interceptor-service does not handle well.

Support Angular 4

We need to upgrade to Angular 4.x and this is the only package that doesn't support Angular 4 in our project.
Can you help to unblock our upgrade by supporting Angular 4?

An error in angular4

我在google搜索到了一个angular2-interceptors的配置例子,我用这个例子配置了拦截器,但是工作起来有个异常,请问您准备支持angular4么?
I google search for an angular2-interceptors configuration example, I use this example configuration of the interceptor, but there is an exception to work, ask you ready to support the angular4?
Angular2 Http拦截器 Interceptor 实现

@angular/cli编译代码时会提示provideInterceptorService不存在,但是当你修改了某些代码后,watch到重新编译时,代码可以正确运行了。。

@Angular/cli Compile the code will prompt provideInterceptorService does not exist, but when you modify some of the code, watch to re-compile, the code can run correctly.

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    CoreModule,
    LayoutModule,
    SharedModule.forRoot(),
    RoutesModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [Http]
      }
    })
  ],
  providers: [HttpInterceptor,
    **provideInterceptorService**([
      HttpInterceptor
    ])
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Support AOT

When I try to build the app with AOT, I get this error message :

Am I missing something or is it just not supported yet ?

Error encountered resolving symbol values statically. Calling function 'provideInterceptorService', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol

Build failed using System JS

Hi

When I run the command npm run build this error occurred Uncaught TypeError: Cannot read property 'InterceptedRequest' of undefined.

But, when I use npm serve this error doesn't occur.

I created a repositry on GitHub to reproduce the error https://github.com/johnidm/ng2-interceptor-problem

I am using System JS to load ǹg2-interceptor: https://github.com/johnidm/ng2-interceptor-problem/blob/master/src/systemjs.conf.js

I am following this set up InterceptorService https://github.com/johnidm/ng2-interceptor-problem/blob/master/src/app/app.module.ts#L29

Custom options to override in the response object

The case is the following:

  1. request made from view
  2. response 200, view processes result
  3. response 404 it is intercepted
  4. response object is returned to fulfill view promise or other subscribers
  5. I do not want view to catch the error nor to process the result because in 3. action was taken

in non typescript scenarios I was simply injected a property handled = true in the response object so the view/controller knew there is nothing further to do with the error message.

What is the best pattern to intercept and prevent bubbling but fulfill view/controller promises or observer subscribers?

Thanks

Cannot prepend url before to Interceptor

Hi Victor,

I having an issue trying to do a Server Url Interceptor to prepend the Api url (http://localhost:5678/api) to every Http request, I debug and its passing trough the Interceptor but the Post request use the actual dev server url (http://localhost:7682) where the app is running so it means that is not adding the new url created in the interceptor to the post request.

Here is my setup:

Login.module.ts

import { NgModule }      from '@angular/core';
import { CommonModule }  from '@angular/common';
import { FormsModule }   from '@angular/forms';
import {
  ModalModule
} from 'ng2-bootstrap';
import {
  HttpModule,
  XHRBackend,
  RequestOptions
} from '@angular/http';
import {
  InterceptorService,
  Interceptor,
  InterceptedRequest,
  InterceptedResponse
} from 'ng2-interceptors';

import { AuthService }         from './auth.service';
import { AuthGuard }         from './auth.guard';
import { LoginComponent } from './login.compontent';
import { ServerURLInterceptor } from './serverURLInterceptor.service';

export function interceptorFactory(
    xhrBackend: XHRBackend,
    requestOptions: RequestOptions,
    serverURLInterceptor: ServerURLInterceptor,
    authService: AuthService

) { // Add it here
  let service = new InterceptorService(xhrBackend, requestOptions);
  service.addInterceptor(serverURLInterceptor);
  return service;
}
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    ModalModule
  ],
  declarations: [
    LoginComponent
  ],
  providers: [
    AuthGuard,
    ServerURLInterceptor,
    AuthService,
      {
        provide: InterceptorService,
        useFactory: interceptorFactory,
        deps: [
          XHRBackend,
          RequestOptions,
          ServerURLInterceptor
         ]
      },
    
  ],
})
export class LoginModule { }

ServerUrlInterceptor.ts

import { Injectable } from '@angular/core';
import {
    InterceptorService,
    Interceptor,
    InterceptedRequest,
    InterceptedResponse
} from 'ng2-interceptors';
import {
    XHRBackend,
    RequestOptions,
    RequestMethod
} from '@angular/http';

@Injectable()
export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
/*        let url = localStorage.getItem('restServerUrl') || ''; */
        let url = 'http://localhost:5678/api';
        request.url = url + request.url;
        if (request.options.method === RequestMethod.Post) {
            request.options.headers.set('Content-Type', 'application/json');
        }
        return request;
    }
}

Auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response, XHRBackend } from '@angular/http';

import { Credentials } from '../login/credentials';
import { UserService } from '../shared/user.service';
import { Observable, BehaviorSubject, Subject } from 'rxjs';
import {
  InterceptorService
} from 'ng2-interceptors';

@Injectable()
export class AuthService {
  public loggedIn: boolean = false;
  public authToken: string = null;
  public changes: Subject<any> = new BehaviorSubject<any>(false);
  constructor(public http: InterceptorService, public userService: UserService) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  public login(credentials: Credentials) {
    // let url = "http://188.166.149.103:9989/api";
    let headers = new Headers();
    let body = {
        username: credentials.username,
        password: credentials.password
    };
    // headers.append('Content-Type', 'application/json');
    return this.http
      .post(
        '/auth/login',
        JSON.stringify(body),
        { headers }
      )
      .map((res: Response) => {
            let payload = res.json();
            let heads = res.headers;
            this.userService.user = payload;
            let user = JSON.stringify(payload);
            this.authToken = heads.get('Authorization');
            localStorage.setItem('user', user );
            localStorage.setItem('auth_token', this.authToken);
            this.loggedIn = true;
            return user;
       }).catch((error: any) => {
         let err;
         switch (error.status) {
           case 400:
            err = {
              status: 400,
              title: 'Ups!',
              msg: 'User or Password incorrect'
            };
            break;
           case 401:
            err = {
              status: 401,
              title: 'Ups!',
              msg: 'Invalid credentials'
            };
           break;
           default:
         }
         return Observable.throw(err);
        });

  }

...

}

Property 'post' does not exist on type 'ServerURLInterceptor'. ?

Hi There, I am using angular2-interceptors but when i am trying to call a POST/GET method then this error occurred : Property 'post' does not exist on type 'ServerURLInterceptor'.

Please suggest me what I do now.

My code is:

interceptorService.ts:

import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';
export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
         console.log(request);
        return request;
        /*
          You can return:
            - Request: The modified request
            - Nothing: For convenience: It's just like returning the request
            - <any>(Observable.throw("cancelled")): Cancels the request, interrupting it from the pipeline, and calling back 'interceptAfter' in backwards order of those interceptors that got called up to this point.
        */
    }
 
    public interceptAfter(response: InterceptedResponse): InterceptedResponse { 
           console.log(response);
           return response;
        /*
          You can return:
            - Response: The modified response
            - Nothing: For convenience: It's just like returning the response
        */
    }
}

app.module.ts:


import { NgModule                                     }   from '@angular/core';
import { BrowserModule                                }   from '@angular/platform-browser';
import { MaterialModule                               }   from '@angular/material';
import { AppComponent                                 }   from './app.component';
import { AppRoutingModule                             }   from './app-routing.module';
import { LoginComponent                               }   from './components/login/login.component';
import { FormsModule                                  }   from '@angular/forms';
import { LoginService                                 }   from './helper/services/login.service';

import { InterceptorService       } from 'ng2-interceptors';
import { ServerURLInterceptor     } from './helper/interceptor/interceptorService';
import { XHRBackend, RequestOptions } from '@angular/http';
export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, serverURLInterceptor:ServerURLInterceptor){ // Add it here
  let service = new InterceptorService(xhrBackend, requestOptions);
  service.addInterceptor(serverURLInterceptor); // Add it here
  console.log("interceptor");
  return service;
}


@NgModule({
  imports:      [ MaterialModule.forRoot(),BrowserModule,AppRoutingModule,FormsModule
                ],
                
  declarations: [ AppComponent,             LoginComponent,
                ],

  providers: [ LoginService,
  ServerURLInterceptor,
  {
      provide: InterceptorService,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerURLInterceptor] // Add it here, in the same order as the signature of interceptorFactory
    }
             ],                                         
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

login.service.ts:


import { Injectable             } from '@angular/core';
import { Observable             } from 'rxjs/Observable';
import { Http                   } from '@angular/http';
import { ServerURLInterceptor     } from '../../helper/interceptor/interceptorService';



@Injectable()
export class LoginService{
    // constructor(private http:Http){}
    constructor(private http:ServerURLInterceptor){}

login(username:string,password:string){
    console.log(username+" , "+password+" in LoginService");
    debugger;
    return this.http
               .post(`http://localhost:4100/login`,{email: username,password:password});
            //    .map(response => response.json().data);
  }
}

Version constraint on peer dependency on rxjs is too tight

The version constraint on the peer dependency for the rxjs library is specified to be exactly 5.0.0-beta.12 in the master branch and 5.0.0 in the feature/versionUpdate branch. This makes this library impossible to use in projects that depend on any other version of the rxjs library. Unless I'm mistaken, I don't think this library depends on rxjs functionality only present in version 5.0.0, so loosening up the version constraints by placing a caret in front of it should make it a whole lot more usable.

how to user ServerURLInterceptor

I have some services using HTTP, I want to modify the request before post, how do I use it? Thank you !

my code can't work .

AuthService.ts

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {

  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http: Http ) { }

  // 登陆
  private url_authLogin = 'auth/login';
  login(account:string,password:string):Promise<User> {
        console.log("登陆:"+account+","+password);
    return this.http.post(this.url_authLogin,JSON.stringify({account:account,password:password}))
               .toPromise()
               .then(response => response.json().data as User  )
               .catch(this.handleError); 
  } 
}

server.url.interceptor.ts

import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';
export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
        request.url = "test"+request.url;
        console.log("intercept url:"+request.url);
        return request; 
    }

    public interceptAfter(response: InterceptedResponse): InterceptedResponse {
        return response;
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { InterceptorService  } from 'ng2-interceptors';
import { XHRBackend, RequestOptions } from '@angular/http';
import { ServerURLInterceptor } from './core/http/server.url.interceptor';

import { AuthService } from './core/auth/auth.service';

// import  ...

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule, 
    NgbModule.forRoot()
  ],
  declarations: [
    AppComponent // ....
  ],
  providers: [
     AuthService,ServerURLInterceptor,
      {
            provide: InterceptorService,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, serverURLInterceptor: ServerURLInterceptor) => {
                let service = new InterceptorService(xhrBackend, requestOptions);
                service.addInterceptor(serverURLInterceptor); 
                return service;
            },
            deps: [XHRBackend, RequestOptions, ServerURLInterceptor] // Here you inject it into the useFactory function above
        }
],
  bootstrap: [AppComponent]
})
export class AppModule { }

Help needed

@voliva I need some help understanding how to handle responses, how to implement the interceptors with a component showing a loading ..?

I've successfully added an interceptor that adds some headers and sets the correct url to the request:

export function interceptorFactory(xhrBackend: XHRBackend,
                                   requestOptions: RequestOptions,
                                   baseInterceptor: BaseInterceptor)
{
	let service = new InterceptorService(xhrBackend, requestOptions);
	
	service.addInterceptor(baseInterceptor);
	
	return service;
}
export class BaseInterceptor implements Interceptor
{
	interceptBefore(request: InterceptedRequest): Observable<InterceptedRequest>|InterceptedRequest
	{
		/*
		 * Set request url
		 */
		let path: string = request.options.url;
		request.options.url = environment.apiUrl + path;
		
		/*
		 * Set api auth and allow cookies to be sent
		 */
		request.options.headers.set("api_token", "xxx");
		request.options.withCredentials = true;
		
		/*
		 * If POST then parse data and build the body
		 */
		if (request.options.method == RequestMethod.Post)
		{
			request.options.headers.set("Content-Type", "application/x-www-form-urlencoded");
			let urlSearchParams = new URLSearchParams();
			let body = request.options.body;
			for (let key in body)
			{
				urlSearchParams.append(key, request.options.body[key]);
			}
			request.options.body = urlSearchParams.toString();
		}
		
		return null;
	}
}

I'd like to set an interceptAfter to parse my response and return appropriate information:

interceptAfter(response: InterceptedResponse): Observable<InterceptedResponse>|InterceptedResponse
	{
		let res = response.response.json();
		switch (res.status)
		{
			case "error":
			{
				return Observable.throw(res.reason);
			}
			case "success":
			{
				return Observable.of(res.data);
			}
			default:
			{
				return Observable.throw("!!!! INVALID RESPONSE STATUS !!!!!");
			}
		}
	}

But with this code I get an error: TypeError: Cannot read property 'ok' of undefined because I'm not returning a response object but a certain imformation.

I know I'm doing something wrong, but how should I achieve my usecase with the interceptors?
And how should I use an interceptor inside my component to get events for showing/hiding a loading??

Any chance of merging my derived library

I have created a derived library from this project long back with quite a lot of additions to this library. I believe its feature complete (support for oauth2 refresh token flows, handling errors, unsubscription, ability to generate mock response/shortcuit, e.t.c)

Here is the link to the library.
https://github.com/1tontech/x-ng4-http-interceptor-dontuse

& corresponding demo for all almost all features is here.

https://github.com/1tontech/x-ng4-http-interceptor-dontuse-demo

However, I don't have time to maintain any bugs that might arise.

I wanted to check with you if you would be interested in merging the code into this project :)

Please let me know your opinion on this?

Body is empty on request when setting requestOptions.body = JSON.stringify({x:1});

With this module my JSON Body is stripped out from request using

requestOptions.body = JSON.stringify({any object});
return this.http.request(path, requestOptions)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return; //response.json();
                }
            });

easy to reproduce, the original Angular 2 http provider works.

Problem importing intercepted-request.ts and intercepted-response.ts

I'm having a problem building my app because it seems that import InterceptedRequest and InterceptedResponse from interceptor are not working. intercepted-request.ts and intercepted-response.ts doesn't exists.

Maybe it'll be better import InterceptedRequest and InterceptedResponse using (no use sufix .ts):

import { InterceptedRequest } from "./intercepted-request";
import { InterceptedResponse } from "./intercepted-response";

I'm not sure if it's a problem with my building system...

Add an example for retry

Can u add an example to the readme on how to do retry. For eg., in OAuth2, when a request is made, if the auth token has expired, the client (browser) needs to refresh auth token using refresh token & make a new request for the previous failed call using this new auth token

If for some reason, both auth & refresh tokens are expired, the user needs to be sent to login page.

Can you update the documentation to reflects flows of this nature

Injecting into ServerURLInterceptor

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

Nothing happens when making HTTP request

Hi, I really like the idea of interceptors.

I need that in an app to catch 401 and redirect to /login.

Here's what I did so far :

  • In my app.module I do have :
providers: [
    provideInterceptorService([
      HttpResponseInterceptor
    ])
]
  • In my HttpResponseInterceptor service :
import { Injectable } from '@angular/core';
import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';

@Injectable()
export class HttpResponseInterceptor implements Interceptor {
  constructor() {
    console.log('Created');
  }
  public interceptBefore(request: InterceptedRequest): InterceptedRequest {
    // Do whatever with request: get info or edit it
    console.log('request start');
    return request;
    /*
     You can return:
     - Request: The modified request
     - Nothing: For convenience: It's just like returning the request
     - <any>(Observable.throw("cancelled")): Cancels the request
     */
  }

  public interceptAfter(response: InterceptedResponse): InterceptedResponse {
    // Do whatever with response: get info or edit it
    console.log('request ended');

    return response;
    /*
     You can return:
     - Response: The modified response
     - Nothing: For convenience: It's just like returning the response
     */
  }
}

When I make an http request :

public connectUser(user: IUser): Observable<Response> {
  return this.http
    .post(`${environment.urlBackend}/user/session`, user);
}

I do not have request start or request ended displayed.

What am I missing ?

Thanks

The post request becomes get

my code:
public interceptBefore(request: InterceptedRequest): InterceptedRequest {

    let jwt = localStorage.getItem('token');
    let authHeader = new Headers();
    if(jwt) {
        authHeader.append('Authorization', 'Bearer ' + jwt);
    }
    authHeader.append('Content-Type', 'application/json;charset=UTF-8');
    request.interceptorOptions={
        headers: authHeader,
    }
    // request.options={
    // headers: authHeader,
    // }
    console.log("请求地址为:"+ request.url)
    return request;
}

when I use
request.options={
headers: authHeader,
}
The post request becomes get

but use:
request.interceptorOptions={
headers: authHeader,
}
don't have that question.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.