我有一个奇怪的问题的初始负载,因为我更新到角最新的路由器(3.0.0-beta.2)如果我执行此代码Angular2路由器则应用
this._router.navigate(['/login']);
不行
在我的应用程序的任何地方它工作正常,除了第一次用户导航到页面,并需要重定向他登录。 没有错误引发,它只是根本不重定向。
这里是我的代码:
main.ts文件:
bootstrap(AppComponent, [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ApplicationConfiguration, provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) => new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig),
deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]
})]);
app.component.ts:
export class AppComponent {
constructor(private appConfig: ApplicationConfiguration, private _router: Router) {
if (!this.appConfig.isUserLoggedIn()) {
this._router.navigate(['/login']);
}
}
}
export const routes: RouterConfig = [
{ path: 'login', component: LogInComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
这可能是因为我没有做的事情是正确的,但此代码用于更新之前的工作。
有没有人知道为什么路由器不会将用户重定向到登录页面?
任何帮助表示赞赏。
解决方案: 在仪表板路线上使用Guard应该有所斩断。
export class AppComponent {
constructor() {}
}
export const routes: RouterConfig = [
{ path: 'login', component: LogInComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [DashboardGuard]},
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
@Injectable()
export class DashboardGuard implements CanActivate {
constructor(private appConfig: ApplicationConfiguration, private _router: Router) {}
canActivate() {
if (this.appConfig.isUserLoggedIn()) { return true; }
this._router.navigate(['/login']);
return false;
}
}
而在main.ts中,您需要将DashboardGuard作为提供程序添加。
浏览器控制台中的任何东西? –
就像我说的,没有...我的感觉是,由于某种原因,可能是某些东西还没有加载?如果你需要我提供其他任何东西,请告诉我。另外,如果我的重定向用户的方法不好,请让我看看一个模板/示例,告诉您如何以最佳方式进行操作。 – Mihai
对不起,没有正确阅读: -/ –