Ande Caleb
Ande Caleb

Reputation: 1204

Run a service before application or components load Angular 7

I am building an application using Angular 7, I have handled the API calls, the JWT Token authentication system using C#, and also updating the LocalStorage() when necessary, when the user logs in and logs out, and all these are working perfectly.

My problem is I want it to run a login check as a middleware within the application rather than on the lifecycle method - ng.onInit(). How do I go about this?

Is there a way to execute lifecycle events as an entry component or service. That is, before any component loads it is able to check if the user is logged in or not and redirect via Router to a desired page.

Upvotes: 2

Views: 9719

Answers (3)

Soukyone
Soukyone

Reputation: 577

You should check for Guard in angular, especially canActivate Guard: https://angular.io/guide/router

A guard is created like this:

@Injectable({
  providedIn: 'root'
})
export class MyGuard implements CanLoad {
 constructor() {}

 canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | 
 Promise<boolean> | boolean {
   const x = true;
   if (x) {
     return true; // It allows access to the route;
   } else {
      // redirect where you want;
     return false; // it doesnt allow to access to the route
  }
 }
}

Then in your routing Module:

{
path: "yourRoute",
canActivate: [MyGuard],
component: YourComponent
}

For authentication, you have a good library that uses guard here: https://www.npmjs.com/package/ngx-auth

Upvotes: 1

Muelsa Prinarnod
Muelsa Prinarnod

Reputation: 74

Guard is based on the routes... so I think you should prefer a module/service solution.

import { APP_INITIALIZER } from '@angular/core';

then add it as a provider like this :

 export function initApp(initService: YourInitService) {
  return () => { 
    initService.Init();
  }
}
    { provide: APP_INITIALIZER,useFactory: initApp, deps: [YourInitService], multi: true } 

Upvotes: 5

Bert Maurau
Bert Maurau

Reputation: 979

You should implement an authGuardService or something like that to use as middleware for your routing (using the canActivate section)

See: https://angular.io/api/router/CanActivate

This prevents routes from being loaded if the canActivate fails the condition (which is preferred when using a login system etc instead of checking in lifecycle hooks).

Upvotes: 0

Related Questions