Diego Unanue
Diego Unanue

Reputation: 6826

Conditional routing change default route in Angular 2

I'm creating an app that when the user enters to the page he goes to the default route wich is "Login" page. What I want is based on a condition (if the user has a local storage variable id, a method called isAuthenticaded() returns true if not false) the user must see the "Polls" page instead of "Login" page. I think two different ways to aprouch this:

1- Change default page: if the method returns true the default page should be "Polls" if not "Login".

2- Redirect the user: if the method returns true the user is redirected to "Polls".

What's the best aprouch to archieve this? How can I do one or both of the point to get conditional routing?

This is my routing config with the isAuthenticated() method:

import {Component} from 'angular2/core'
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import 'rxjs/Rx'; // load the full rxjs
import {RouteConfig, ROUTER_DIRECTIVES, Router} from 'angular2/router';


import { PollsComponent } from './pollslist/pollslist.component'
import { Login } from './login/login'

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES, Login, PollsComponent],
    providers: [HTTP_PROVIDERS]
})

@RouteConfig([
    { path: '/login', name: 'Login', component: Login, useAsDefault: true },
    { path: '/polls', name: 'Polls', component: PollsComponent }

])

export class AppComponent {
    isAuthenticated() {
        if (localStorage.getItem('id')) {
            return true;
        } else {
            return false;
        }

    }

}

Upvotes: 2

Views: 4830

Answers (2)

kemsky
kemsky

Reputation: 15271

Router definition has loader parameter:

loader : () => Promise<Type>

that allows to determine component type dynamically and async.

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657366

You can check in

  • @CanActivate() and navigate to a different route using router.navigate()

  • or create a custom <router-outlet> where you do this.

For details see https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492#.f76jyafdn

See also Check if the user logged in on any page change in Angular 2

Upvotes: 2

Related Questions