Angular 2路由异步解析在导航时无法保留位置

15

当用户尝试访问未允许的页面时,我希望将其导航到错误页面。但问题是,在这种情况下,skipLocationChange不起作用。它会导航到错误页面,但URL会更改为根目录。如何保留用户提供的原始URL?

resolve(route: ActivatedRouteSnapshot): Observable<any|boolean>|boolean {
    return this.apiclientService.get('cars/' + route.params['id']).map(
        response => {
            if (response.data.user_id === this.authService.user().id) {
                return response.data;
            }

            this.router.navigate(['/404'], { skipLocationChange: true });
            return false;
        }
    ).catch(error => {
        this.router.navigate(['/404'], { skipLocationChange: true });

        return Observable.of(false);
    });
} 

你为什么不使用守卫(guards)呢?https://angular.io/docs/ts/latest/guide/router.html#!#guards 我不确定这是否能解决你的问题,但我认为这正是守卫的用途。 - Günter Zöchbauer
我尝试了Guard(canActivate),但问题仍然存在,而且不能像resolve一样将数据传递给控制器。如果您有任何示例,我会非常感激。 - izupet
抱歉,我不知怎么地以为你的代码是在组件中。无论如何,我指的是“resolve”。如果能提供一个Plunker来重现问题并查看路由,那就太好了。 - Günter Zöchbauer
@izupet,你是怎么解决的? - securecurve
2个回答

1

我认为skipLocationChange实际上是起作用的。问题在于Angular没有导航到新路由,因为守卫失败了。如果你想捕获失败的URL,请检查route: ActivatedRouteSnapshot参数。


0
问题在于this.route是在根级别注入的,因此它将成为根路由。
您可以遍历路由以找到您感兴趣的路由。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接