Angular2 router.navigate()不工作第一次
我有以下途径定义:Angular2 router.navigate()不工作第一次
export const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuardService] },
{ path: 'sites', component: SiteIndexComponent, resolve: { siteSummaries: SiteSummariesResolve }, canActivate: [AuthGuardService] },
{ path: 'qa-tasks', component: QaTaskIndexComponent, resolve: { investigations: InvestigationsResolve, reviews: ReviewsResolve }, canActivate: [AuthGuardService] },
{ path: 'error', component: ErrorComponent },
{ path: '**', redirectTo: '' }
];
我的应用程序。用户可以看到基于其角色包括他们的“落地”(主页)完全不同的页面。我用我的HomeComponent路由用户到正确的着陆页基于这样的角色:
export class HomeComponent implements OnInit {
private roles: any;
constructor(private router: Router,
private authService: AuthService) { }
ngOnInit() {
var currentUser = this.authService.getCurrentUser();
this.roles = currentUser.roles;
this.redirect();
}
private redirect() {
var route;
if (this.inRole('site-user-role')) {
route = 'sites';
}
else if (this.inRole('qa-user-role')) {
route = 'qa-tasks';
}
if (route) {
this.router.navigate([route]);
}
else {
this.router.navigate(['error']);
}
}
private inRole(role) {
return _.includes(this.roles, role);
}
}
当HomeComponent
登录后第一次加载时,路线不浏览到,例如,“网站'路线,但奇怪的是它解决了siteSummaries依赖关系。第一次重定向失败后,我可以导航到另一条路线,然后尝试导航到“路线”,并将其正确重定向到“网站”路线。
为什么初始导航不起作用?基于关于导航()不工作的其他类似问题,我试图改变我的路线'/网站'和'./sites',但无济于事。
更新 看起来它与解决路由依赖关系有关。如果重定向到我的redirect()
函数中的“错误”路由,它会在第一次成功执行。如果我将“resolve
”添加到我的“错误”路线中,它将无法在第一次导航到它。奇怪的是它使HTTP调用来实现依赖。这是一个问题,它不等待navigate()
的承诺的回报?
更新2 这里是要求等级:
export class SiteIndexComponent implements OnInit {
public siteSummaries: any;
public totalRegisteredCount: number;
public totalscreenFailedCount: number;
public totalinProgressCount: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.siteSummaries = this.route.snapshot.data['siteSummaries'];
this.totalRegisteredCount = this.getTotal('registeredCount');
this.totalscreenFailedCount = this.getTotal('screenFailedCount');
this.totalinProgressCount = this.getTotal('inProgressCount');
}
private getTotal(prop): number {
var total = 0;
_.forEach(this.siteSummaries, function (summary) {
return total += summary[prop];
});
return total;
}
}
@Injectable()
export class SiteSummariesResolve implements Resolve<any> {
constructor(private sitesService: SitesService) { }
resolve(route: ActivatedRouteSnapshot) {
return this.sitesService.getSiteSummaries();
}
}
getCurrentUser(): any {
var currentUser = sessionStorage.getItem('currentUser');
if (!currentUser) {
return null;
}
return JSON.parse(currentUser);
}
更新3 我扔进我app.component
这样的:
private navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
console.log('started: ' + JSON.stringify(event));
}
if (event instanceof NavigationEnd) {
console.log('ended: ' + JSON.stringify(event));
}
if (event instanceof NavigationCancel) {
console.log('cancelled:' + JSON.stringify(event));
}
if (event instanceof NavigationError) {
console.log('error:' + JSON.stringify(event));
}
}
在次当它无法加载路线(第一次),首先是NavigationStart的事件实例,然后是NavigationCancel的实例。以下是NavigationCancel上的事件:{"id":2,"url":"/sites","reason":""}
。正如你所看到的,没有理由......
我仍然不知道为何取消我的路线导航,但我已经想出了一个解决办法是将ngInit
更改为以下内容:
ngOnInit() {
var currentUser = this.authService.getCurrentUser();
this.roles = currentUser.roles;
var that = this;
setTimeout(function() { that.redirect(); }, 50);
}
结束语在超时我重定向调用允许的事情是用不易察觉的延迟除外正常工作。这似乎是某种时间问题?如果我尝试将超时设置为20,它也不起作用。
使用这种方法,我得到了'ERROR TypeError:this.redirect不是一个函数,即使我定义它并像这样使用它:'private redirect(path:string):void' –
@ An-droid注意'that =这个' – BeaverusIV
这套setTimeout解决方法在我尝试在''CustomErrorHandler'''内导航时为我工作... – jonas
你不应该在构造函数中做副作用的事情。相反,实施ngOnInit:
class HomeComponent implements OnInit {
ngOnInit() {
// navigate things...
}
}
尝试一下本作路由
import { Routes, RouterModule } from '@angular/router';
export const router: Routes = [
{ path: '', redirectTo: 'main', pathMatch: 'full'},
{ path: 'main', component:AdminBodyComponent },
{ path: 'admin', component:AdminComponent },
{ path: 'posts',component:PostsComponent},
{ path: 'addposts',component:AddPostComponent}];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
step2:
inject into your .ts file
constructor(
private router:Router,
...
)
step3:
this.router.navigate(['/addposts']);
getCurrentUser是一个异步操作? – DeborahK
你的路由可能没问题。你能分享一下'SiteIndexComponent'和'SiteSummariesResolve'吗? –
@MezoIstvan更新 – im1dermike