1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Conditional routing change default route in Angular 2

Discussão em 'Angular' iniciado por Diego Unanue, Maio 22, 2025.

  1. Diego Unanue

    Diego Unanue Guest

    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;
    }

    }

    }

    Continue reading...

Compartilhe esta Página