问题描述
假设我有一个带有这样参数的路由(在 Angular 2 中):/user1/products/:id
,它可能有像 /user1/products/3/这样的子路由评论
.
Say I have an route with a param like this (in Angular 2): /user1/products/:id
, which could have child routes like /user1/products/3/reviews
.
当我导航到 /user1/products/-1
时,我会检查我的服务器,如果该产品不存在,我想呈现一个 404 页面而不影响浏览器历史记录.
When I navigate to /user1/products/-1
, I check with my server and if the product doesn't exist, I want to render a 404 page without affecting the browser history.
使用 router.navigate(['/404'])
或 router.navigateByUrl('/404')
似乎不起作用,因为它同时添加了 /user1/products/-1
和 /404
到浏览器历史记录.
Using router.navigate(['/404'])
or router.navigateByUrl('/404')
doesn't seem to work because it adds both /user1/products/-1
and/404
to the browser history.
意味着当我在浏览器中按下 Back 按钮时,我会返回到 /user1/products/-1
,它会立即重定向到 /404
我基本上被困在 /404
.
Meaning when I press the Back button in the browser, I go back to /user1/products/-1
which is immediately redirected to /404
and I'm essentially stuck at /404
.
在 ExpressJS 中,我们会执行类似 next()
的操作来将请求传递给我们的 404 处理程序.Angular 2 中是否有客户端等价物?
In ExpressJS, we would do something like next()
to pass the request to our 404 handler. Is there a client-side equivalent in Angular 2?
推荐答案
更新
在新的路由器 V3 中,您可以使用 https://angular.io/guide/router#canactivate-requiring-authentication
In the new Router V3 you can use guards as explained in https://angular.io/guide/router#canactivate-requiring-authentication
原创
我认为您应该使用 @CanActivate() 进行检查.如果您在 @CanActivate()
中转发,则不应将无效 URL 添加到历史记录中(未尝试)
I think you should use @CanActivate() to do the check. If you forward in @CanActivate()
the invalid URL shouldn't be added to the history (not tried)
另见 https://github.com/angular/angular/issues/4112 如何在 @CanActivate()
这篇关于当路由参数无效时,角度 2 路由到 404 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!