3

I have written this intercept method:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
  console.log('EVENT:', event);
}, (err: HttpErrorResponse) => {
  const message = err.error.message;
  if (message == 'You need to activate your account!') {
    // TODO: Redirect to '/auth/not-activated'
  }
});
}

If I receive from server specific error message, I need to redirect user to address /auth/not activated

How can I achieve that?

I have already tried

this.router.navigateByUrl(url);

but this is not working.

User
  • 314
  • 2
  • 3
  • 15

1 Answers1

0

This same i suggested in my answer before

register interceptor like as below

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { UnauthorizedInterceptor } from './../auth/UnauthorizedInterceptor';
@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: UnauthorizedInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

Read : UNAUTHORIZED INTERCEPTER FOR ANGULAR

import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
    constructor(
        private router: Router
    ) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).catch((err: any) => {
            if (err instanceof HttpErrorResponse && err.status === 401) {
                this.router.navigate(['/login'], {
                    queryParams: {
                        redirectTo: document.location.pathname
                    }
                });

                // this response is handled
                // stop the chain of handlers by returning empty
                return Observable.empty();
            }

            // rethrow so other error handlers may pick this up
            return Observable.throw(err);
        });
    }

try out this , make use of catch method on observable and use navigate method fo route to navigate

return next.handle(req).catch(
(err: HttpErrorResponse) => {
   this.router.navigate(['/auth/not-activated']);
    return Observable.throw(err);
  });
User
  • 314
  • 2
  • 3
  • 15
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • actually there is one warning Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS – User Apr 05 '18 at 18:24
  • @User - follow the article given helps you and code given – Pranay Rana Apr 05 '18 at 18:31
  • @User- share your full code some where there might be you are creating cyclic dependancy : https://stackoverflow.com/questions/47091872/angular-4-cannot-instantiate-cyclic-dependency-injectiontoken-http-interceptor/47097413%E2%80%A6 – Pranay Rana Apr 05 '18 at 18:37
  • Ok your edited solution works perfectly when I have only ONE interceptor, but not when there are multiple doing similar thing (only error and url are different) – User Apr 05 '18 at 18:43
  • @User - have you done like this https://stackoverflow.com/questions/45633102/add-multiple-http-interceptors-to-angular-application ? – Pranay Rana Apr 05 '18 at 18:46
  • @User by looking at your code AccountSubscribedInterceptor this get called after your validation i.e. redirect code – Pranay Rana Apr 05 '18 at 18:55
  • yes it is, the expected behavior is, that when one pass without redirect, second should be called, but if first throws an error, second shouldn't be loaded – User Apr 05 '18 at 18:58
  • @User - third one will get execute in any case even it snot authenticated , if possible can i see code – Pranay Rana Apr 05 '18 at 19:00
  • all codes are same as one above, there are only different error messages – User Apr 05 '18 at 19:02
  • @User - can you please provide full code, i want to see if you are injecting anything in your constructor of injector – Pranay Rana Apr 05 '18 at 19:16