当路由参数无效时,angular 2 路由到 404 页面 [英] angular 2 route to 404 page when route param is invalid
问题描述
假设我有一个带有这样参数的路由(在 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.
意思是当我在浏览器中按下返回按钮时,我返回到/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()
这篇关于当路由参数无效时,angular 2 路由到 404 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!