Angular CanActivate vs Resolve




Asked on July 27, 2018
When to use Angular CanActivate guard and when to use Resolve guard and what is difference between them?


Replied on July 28, 2018
CanActivate

CanActivate is an Angular interface. It guards a link and allow to access conditionally such as in user authentication application. We can enter into application only after login. So the application links will be guarded by CanActivate and will be accessible only after login. Find the sample code.

@Injectable()
export class AuthGuardService implements CanActivate {
     
  constructor(private authService: AuthService, private router: Router) {
  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
    console.log('Url:'+ url);
    if (this.authService.isUserLoggedIn()) {
        return true;
    }
        this.authService.setRedirectUrl(url);
        this.router.navigate([ this.authService.getLoginUrl() ]);
    return false;
  }
}


Resolve

Angular provides Resolve interface with resolve method declaration. To create a Angular Resolve guard, we need to create a class by implementing Resolve interface. Resolve guard is used in the scenario where before navigating to any route we want to ensure whether there is data available or not. If there is no data then it has no meaning to navigate there. It means we have to resolve data before navigating to that route. Find the sample code.

@Injectable()
export class CountryDetailResolver implements Resolve<Country> {
  constructor(private countryService: CountryService, private router: Router) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Country> {
    let id = route.paramMap.get('country-id');
    console.log('Resolving for country id:' + id);
   
    return this.countryService.getCountry(id).map(country => {
      if (country) {
        return country;
      } else {
        this.router.navigate(['/country/countryList']);
        return null;
      }
    });
  }
}





Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us