Angular2 router.navigate()第一次不工作

时间:2017-04-20 13:25:10

标签: angular angular2-routing

我定义了以下路线:

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: '' }
];

我的应用的用户根据他们的角色看到完全不同的页面,包括他们的#34;登陆" (主页。我使用我的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'和' ./ 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":""}。如你所见,没有理由......

3 个答案:

答案 0 :(得分:7)

我仍然不知道为什么它取消了我的路线导航,但我想出的办法是将ngInit更改为以下内容:

ngOnInit() {
    var currentUser = this.authService.getCurrentUser();
    this.roles = currentUser.roles;
    var that = this;
    setTimeout(function () { that.redirect(); }, 50);
}

在超时时包装我的重定向调用允许事物按预期工作,但不可察觉的延迟除外。这似乎是某种时间问题?如果我尝试将超时设置为20,它也无法正常工作。

答案 1 :(得分:0)

你不应该在构造函数中做副作用。相反,实现ngOnInit:

class HomeComponent implements OnInit {
  ngOnInit() {
    // navigate things...
  }
}

另请参阅:Difference between Constructor and ngOnInit

答案 2 :(得分:0)

尝试使用此路由

&#13;
&#13;
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']);
&#13;
&#13;
&#13;