Redirect page without using a component in Angular5

Issue

After login or registration, I want to create a class that will determine the role of the authenticated user and redirects him to the correct page. Is there another way of doing this rather than using an angular component? What I don’t like about the component page is that the page is loaded before redirection, even though the component doesn’t display anything, it still uses the base template from app.component.

I’m using Keycloak for registration and login (meaning it’s not part of the app I’m developing and I can only set the redirectUri). So I can only redirect to one URL.

Solution

Here is the general idea I used for this case.

Create a login component which has a blank template (.html).

Make sure to set the routing for it as well.

app.routing.ts

{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginScreenComponent},

login-screen.component.ts

constructor(private keyCloakService: KeyCloakService, private router: Router) {}
ngOnInit() {
      // Do a call where you get logged in user and it's role, ex:
      let role = this.keyCloakService.getUserRole(); 

      // Do a redirect based on that role
      if(role == "admin){
           this.router.navigate(["/admin"]);
      }

  }

Once you get this working, I would also suggest adding AuthGuard to your role routes.

There is also second, more clean, approach which you might take, but is a bit more complicated if you didn’t work with AuthGuard before.

In short, you would handle the solution I gave you in your AuthGuard service. That way you will avoid creating a login component, but the outcome will be the same.

And regarding the template of app.component.ts, the common practice is that you only have <router-outlet></router-outlet> in it, therefore you don’t load any layout, and you have more freedom over it.

EDIT (Answer to question below):
You can use your secure and non secure layout through routing. For instance:

  {
    path: 'admin',
    component: AdminLayoutComponent,
    canActivate: [Guard],
    children: [
      {
        path: '',
        loadChildren: './components/app-admin/secure.module#SecureModule'
      }
    ]
  }

And do the same thing for public layout. That way you will have only in your app.component, and will have much more freedom for redirects, etc.

Answered By – Dino

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.