Best way to handle authenticated areas in app?

Maybe an http guard?

I found the following tutorial about how to extend the http class:

In the interceptor your could do then something like following (for each route which should be guarded…post/get/delete/put/request):

 // 1. Declare observable
 private requestInterceptedSource: Subject<number> = new Subject<number>();
 requestIntercepted:Observable<number> = this.requestInterceptedSource.asObservable();

// Override get/post/delete/put/request like
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(url,options).catch((errorResponse:Response) => {
       // If you rather like to only forward to login page on 400, just check errorResponse.status == 400 for example
         this.mySource.next(errorResponse.status); 
         return Observable.empty();
    });
}

And finally in your app.component subscribe to the observable of the http-interceptor. If something is emitted, set the root navigation to the root page aka redirect to login page if user was not authenticated to execute the http post/get/put/etc.

1 Like