3

I have an Angular project where I set up a route with a resolve like this:

{
  path: 'participants/detailedView/:participantId',
  component: ParticipantDetailedViewComponent,
  resolve: {
    participant: ParticipantResolve,
  },
},

I also have a HTTP Interceptor in my project in order to intercept any 401 error and redirect to the login page:

@Injectable()
export class JwtInterceptor implements HttpInterceptor {

  constructor( public auth: AuthenticationService,
               private router: Router ) {
  } 

  public intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    let url: string = request.url;
    let method: string = request.method;
    console.log(`JwtInterceptor url=${url},   method=${method}`);

    return next.handle( request ).do( ( event: HttpEvent<any> ) => {
        console.log(`successful reply from the server for request=${request.urlWithParams}`);
    })
    .catch((responseError: any) => {

      // ResponseError Interceptor
      if (responseError instanceof HttpErrorResponse) {
        console.error('response in the catch: ', responseError);

          if ( responseError.status === 401 ) {
            let errorMsg: string = '';

            if ( responseError.statusText === 'Invalid credentials' ) {
              errorMsg = 'Username or password is incorrect';
            }

            // redirect to the login route
            this.router.navigate(['/login'], {queryParams: {msg: errorMsg}});
            return Observable.empty();
          }

        return throwError(responseError);
      }


      let error = new HttpErrorResponse({
        status: 500,
        statusText: 'Unknown Error',
        error: {
          message: 'Unknown Error'
        }
      });
      return throwError( error );

    }) as any;
  }
}

If a 401 error is thrown during the HTTP call in the resolve, my Interceptor will redirect the user to the login page.

At this point I would like to know what was the targeted URL in order to be able to redirect the user to the page he wanted to see after he successfully login.

So my Question is: From the HTTP Interceptor, how can I know the targeted URL ?

So far the only solution I found is to listen to NavigationStart event in a service, store the value and use that in my HTTP Interceptor. I don't really like this solution and I think there should be a better way but I can't find it.

Any Ideas ?

Tonio
  • 4,082
  • 4
  • 35
  • 60

0 Answers0