条件路由更改Angular 2中的默认路由

问题描述 投票:1回答:2

我正在创建一个应用程序,当用户进入页面时,他会转到默认路径,即“登录”页面。我想要的是基于一个条件(如果用户有一个本地存储变量id,一个名为isAuthenticaded()的方法返回true,如果不是false)用户必须看到“轮询”页面而不是“登录”页面。我认为有两种不同的方法可以解决这个问题:

1-更改默认页面:如果方法返回true,则默认页面应为“轮询”,如果不是“登录”。

2-重定向用户:如果方法返回true,则用户被重定向到“Polls”。

实现这一目标的最佳方法是什么?如何获得有条件路由的一个或两个点?

这是我使用isAuthenticated()方法的路由配置:

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

    }

}
javascript angular typescript angular2-routing
2个回答
2
投票

你可以登记入住

  • @CanActivate()并使用router.navigate()导航到不同的路线
  • 或者在这里创建一个自定义的<router-outlet>

有关详细信息,请参阅https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492#.f76jyafdn

另见Check if the user logged in on any page change in Angular 2


0
投票

路由器definitionloader参数:

loader : () => Promise<Type>

允许动态和异步确定组件类型。

© www.soinside.com 2019 - 2024. All rights reserved.