jomalone_jia
jomalone_jia

Reputation: 53

how to intecept custom http in angular2

i create a custom http extends HttpInterceptor, like this:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private router:Router,
              private store: Store<fromAuth.State>){

  }

  intercept(req: HttpRequest<any>,
            next: HttpHandler
  ): Observable<HttpEvent<any>> {

    return next.handle(req).do(evt => {
      console.log(evt);
      if(evt instanceof HttpRequest){
        console.log(evt);
      }
      if (evt instanceof HttpResponse) {
        if(evt.status === 401){
          this.router.navigateByUrl('/');
        }else if(evt.status === 202){
          console.log(evt);
          this.store.dispatch(new auth.LoginSuccessAction(evt.body));
        }else if(evt.status === 200){
          console.log(evt);
        }
        else{
          console.log('other')
        }
      }
    });

  }
}

and then add this in my appModule providers :

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

now it worked,my http can be intercepted with httpClient!

then i created a custom http by extends Http:

@Injectable()
export class AuthHttp extends Http {


....

also add in appModule providers:

{AuthHttp},

this AuthHttp is still worked! But i found that my AuthInterceptor could not intercept AuthHttp how to fixed this ? thank!

Upvotes: 0

Views: 47

Answers (0)

Related Questions