Search code examples
angularangular2-routingangular-guards

resolver with a guard in angular4 with ASP.NET Web Api 2


I am working on angular 4 Project with Asp.NET Web API 2. I want to check if the user is authorized before he enters the admin section. I tried to set the resolver in the routing of angular, like that:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    return this.profile.getProfile()
             .map(result => { setAuthorized(); return result;})
             .catch(res => { return Observable.of(new Profile()); });
 }

setAuthorized() function will set the authorization in a global variable so it can be checked with the function isAuthorized() and the authorization guard:

if (this.route.firstChild != null) {
   return this.route.firstChild.data.map( res => {
     if (isAuthorized()) {
       return true;
     }
   });
 } else {
   return Observable.of(false);
 }

the routing is:

const routes: Routes =
  [
     {path: ':lang', component: LanguageComponent, 
        children: [
           { path: 'dashboard', component: DashboardComponent, resolve: { authority: AuthorityResolverService} },
           { path: 'admin', component: AdminComponent, canActivate: [AuthorizedGuard], resolve: { authority: AuthorityResolverService}},
        ]}
  ];

Everything seems to be working correctly. But the problem is when I click F5 or when I copy the URL and open it in a new window, I will be always redirected to the error page. when I monitor the workflow, it shows that it did not call the resolver when I am trying to reach the URL directly:

localhost/admin

I am not receiving any error, but I am being redirected always. Any Ideas?


Solution

  • It expected behavior. When you hit the route, guard will be ran first and if canActivate returns true then resolver will be ran. Since your guard will return false, your resolver will not be called (and it should not be).

    Which means you might want to redesign your logic a bit in a way that you put getting profile/authorization into guard becaue that's what guard really is: it should check some condition and resolve based on it. Your condition is that user is authenticated so that belongs to guard.

    Resolvers purpose is to get the data needed for component once the user is allowed to activate component.