27185

Returning an Observable from canActivate method and redirect on false

Question:

I have been searching for a solution with no luck. I need to call the server if a user is authorized and i need canActivate method to wait for the result for that call. But i can`t seem to put pieces together. Below is my code, my question is in the comments of the code.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { let user: EUser = new EUser(); user.sessionId = localStorage.getItem("sessionId"); //I am not sure how to implement this part. // I need to recieve the response and get user.isAuthorized value and return it // as an observable. this.authenticationService.isAuthorized(user).subscribe((user)=>{ //Here i need to get user.isAuthorized and //if the value is false, i need to navigate to login with this.router.navigate['login'] and return it. //if the values it true, i need the code continue as it is. }); }

AuthenticationService

isAuthorized(user:EUser){ return this.http.post(ConnectionHelper.SERVER_URL+ ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user).map(res => res.json()); }

Answer1:

Your approach is correct, you just need to map the server response to a bool value. For example:

export interface AuthState { username:string; sessionId:string; isAuthorized:boolean; } isAuthorized(user:EUser): Observable<AuthState> { return this.http.post(ConnectionHelper.SERVER_URL+ ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user) .map(res => res.json()); } // Inject Router instance in the constructor of the guard class // import required rxjs operators canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { let user: EUser = new EUser(); user.sessionId = localStorage.getItem("sessionId"); return this.authenticationService.isAuthorized(user) .map(user => user.isAuthorized) .do(auth => { if(!auth){ this.router.navigate(['/login']); } }); }

Recommend

  • EGID and RGID incorrectly displayed in ps o/p?
  • Send CTRL_C/SIGINT to a process from C#
  • InProc session data disapearing
  • Sending commands to stdin and sending end of transmit (Ctrl+D)
  • converting curl call to python requests
  • http request every x seconds in angular
  • Duplicates in temporal history table
  • Angular: Binding to a observable property of service -> value doesn't update
  • How to make object in List eligible for garbage collection?
  • Angular2 - How to Abort/cancel running http request calls?
  • Convert a plain string[] into a Observable and concat it to another Observable using RxJS 5
  • KnockoutJS Forcing A Computed Observable to Re-Compute
  • Can I return raw json response in angular2
  • Knockout.js mapping options being ignored on nested values
  • At what point is code reordering in C++ optimization stopped?
  • How to ignore all from an observable if the other observable has data in RxJS?
  • Does as-if rule prevent compiler reordering of accesses to global/member variables?
  • Wait for subscription to complete
  • Does many include's (in “case”) in ASP classic hurt the performance of the server?
  • How to prevent TreeItem selection?
  • Catch in Observable stops HTTP Calls from Observable.interval
  • How to keep button state across different pages?
  • How to autoplay video in angularjs?
  • Angular5 Service Worker update(SWUpdate) not detecting on firefox. Working on chrome
  • Execute JavaScript code once a browser window/tab is opened for the first time
  • How to make R's read_csv2() recognise the text characters properly
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • Implementation of State Monad
  • How can I extract results of aggregate queries in slick?
  • OOP Javascript - Is “get property” method necessary?
  • How do I pass the string value parameter of the selected list item from an auto-populated dropdown l
  • PHP - How to update data to MySQL when click a radio button
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Bitwise OR returns boolean when one of operands is nil
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal