Scottie
Scottie

Reputation: 11308

In Angular 2, how can I use a different route during runtime?

I have a flag set that determines if the user is logged in or not. If not, I want to use the login routes, which only has login and login/forgotpassword. Otherwise, I want to use my regular route.

In my app.module, how can I check my flag and load a different route file depending on how it's set?

Here's my app.module:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { LoginAppRoutes } from "./login.routes";
import { AppRoutes } from "./routes";

@NgModule({
    imports: [BrowserModule,
    RouterModule.forRoot(LoginAppRoutes)], <-- How do I change this?
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 0

Views: 50

Answers (1)

cyr_x
cyr_x

Reputation: 14257

I would recommend to use a route guard which checks if the user is logged in, if not goto login route, else render the route. (see: angular docs) And apply that guard to all your "root | parent" routes you want to be protected.

Upvotes: 3

Related Questions