angular2路线无法正常工作

时间:2016-07-05 07:27:34

标签: redirect angular router

我使用angular2 rc3和angular2 / router 3.0.0-alpha.8来做我的路由器: 这是我的代码:

bootstrap(AppComponent, [HTTP_PROVIDERS, APP_ROUTER_PROVIDERS, AUTH_PROVIDERS,
    {
        provide: AuthHttp,
        useFactory: (http:Http) => new AuthHttp(new AuthConfig({tokenName: 'jwt'}), http),
        deps: [Http]
    },
    {
        provide: TranslateLoader,
        useFactory: (http:Http) => new TranslateStaticLoader(http, 'app/i18n', '.json'),
        deps: [Http]
    },
    {provide: LocationStrategy, useClass: PathLocationStrategy},
    // use TranslateService here, and not TRANSLATE_PROVIDERS (which will define a default TranslateStaticLoader)
    TranslateService,
    ApiService,
    CookieService,
    AuthenticationService

]).catch(err => console.error(err));

我的路由器是:

export const routes:RouterConfig = [
    ...AccountRouters,
    ...DealOverviewRouters

];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)
];


export const AccountRouters: RouterConfig = [
    {
        path: 'account', component: AccountComponent
    },
    {
        path: 'login', component: LoginComponent
    },
];

export const DealOverviewRouters:RouterConfig = [
    {
        path: '',
        redirectTo: '/deal-overview',
        terminal: true
    },
    {
        path: 'deal-overview', component: DealOverviewComponent
    }
];

然后在我的app.component.ts中:

constructor(public translate:TranslateService, private _service: AuthenticationService, private _router: Router) {
        this.isLogin = _service.isLogin;
        console.log(_service.isLogin);
}

ngOnInit() {
        // this._service.checkCredentials();
        if(!this.isLogin) {
           console.log(1111);
            this._router.navigateByUrl('/login');
        }
}

它真的在我的控制台日志上打印1111; 但重定向到/login无效。

我可以直接访问我的localhost:3000/login页面,没有任何错误。 但只有this._router.navigateByUrl('/login')无效。

1 个答案:

答案 0 :(得分:1)

我在使用新路由器时遇到以下语法问题:

export const routes:RouterConfig = [
    ...AccountRouters,
    ...DealOverviewRouters
];

而是手动将它们全部放入一个const中并尝试:

export const routes:RouterConfig = [
    {
        path: '',
        redirectTo: '/deal-overview',
        terminal: true
    },
    {
        path: 'deal-overview', component: DealOverviewComponent
    },
    {
        path: 'account', component: AccountComponent
    },
    {
        path: 'login', component: LoginComponent
    }
];