javascriptangulartypescriptangular2-routing

Conditional routing change default route in Angular 2


I'm creating an app that when the user enters to the page they go to the default route which 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 can think two different ways to approach 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 approach to achieve 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;
        }

    }

}

Solution

  • You can check in

    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