Learn to protect Angular 2 routes with canActivate Guard for Firebase users. Route guard prevents unauthorized users to access the Angular app routes.
seen from Canada
seen from China

seen from United States
seen from China

seen from Jordan
seen from United States
seen from United States
seen from United States
seen from United States
seen from China
seen from Ireland
seen from China
seen from Egypt
seen from Türkiye
seen from China
seen from Hungary

seen from Malaysia
seen from United States
seen from China

seen from United States
Learn to protect Angular 2 routes with canActivate Guard for Firebase users. Route guard prevents unauthorized users to access the Angular app routes.
Angular 2: Preload Resource Data
Preloading, or bootstrapping your application is done in Angular 2 using CanActivate decorators.
@CanActivate((next, prev) => boolean | Promise<boolean>)
CanActivate can be used to implement authorization in your application, to check if user is logged-in on specific component, or to load any necessarily data before rendering component.
Consider this application with these different routes:
@RouteConfig([ {path:'/cities', name: 'CityList', component: CityListComponent, useAsDefault: true}, {path:'/city/:id', name: 'CityDetail', component: CityDetailComponent} ])
We would like to render CityDetail: /city/:id But the model by id is not loaded in CityDetail, but in the CityList, so here we can use CanActivate to load all necessarily data before rendering the component, and share same CanActivate on nested component if necessarily.
How to:
First we create a function that have reference to the application injector, so we can have reference to the different service in the bootstrap.
bootstrap(ApplicationComponent, [ CityService, provide(LocationStrategy, {useClass: HashLocationStrategy}) ]).then((appRef: ComponentRef) => { appInjector(appRef.injector); });
let appInjectorRef: Injector; export const appInjector = (injector?: Injector):Injector => { if (injector) { appInjectorRef = injector; } return appInjectorRef; };
Next, we add CanActivate to the CityDetail component.
@CanActivate(() => cityActivate()) export class CityDetailComponent implements OnInit
and the cityActivate is implemented like this:
export const cityActivate = () => { let injector: Injector = appInjector(); // get the stored reference to the injector let cityService: CityService = injector.get(CityService); let router: Router = injector.get(Router); // return a boolean or a promise that resolves a boolean return new Promise((resolve) => { cityService.load().subscribe((result) => { if (result.length > 0) { resolve(true); } else { router.navigate(['CityList']); resolve(false); } }); }); };
Here we use the CityService to load the models and then resolves to true when the data is ready.
More links:
CanActivate Decorator
Angular2 Issue 6611