当路由参数无效时,角度2路由到404页面

时间:2016-04-13 13:12:45

标签: angular-ui-router angular

假设我有一个带有这样的参数的路径(在Angular 2中):/user1/products/:id,它可能有/user1/products/3/reviews之类的子路径。

当我导航到/user1/products/-1时,我会检查我的服务器,如果产品不存在,我想在不影响浏览器历史记录的情况下呈现404页面。

使用router.navigate(['/404'])router.navigateByUrl('/404')似乎不起作用,因为它会将/user1/products/-1/404添加到浏览器历史记录中。

当我按下浏览器中的后退按钮时,我会回到/user1/products/-1,然后立即重定向到/404,我基本上停留在{{1} }}

在ExpressJS中,我们会像/404那样将请求传递给404处理程序。 Angular 2中是否存在客户端等效项?

4 个答案:

答案 0 :(得分:8)

<强>更新

在新的路由器V3中,您可以使用https://angular.io/guide/router#canactivate-requiring-authentication

中所述的防护

<强>原始

我认为您应该使用@CanActivate()进行检查。如果您在@CanActivate()转发,则无效的网址不应添加到历史记录中(未尝试)

另请参阅https://github.com/angular/angular/issues/4112了解如何在@CanActivate()

中使用DI

答案 1 :(得分:3)

好的,这已经实施,但没有详细记录。

根据文件:
$cards = array(); // get cards per range for($i = 0; $i < 116; $i++) { // range 1: $cards[] = mt_rand(35, 74); // for the fun, let's also do range 2: if($i < 46) { $cards[] = mt_rand(75, 106); } } // range 3: (and range 4) $rare = array(); $superrare = array(); for ($i = 107; $i <= 134; $i++) { $rare[] = $i; // range 4: if ($i <= 114) { $superrare[] = $i + 28; } } shuffle($rare); shuffle($superrare); // not the best choice of randomness (check: http://stackoverflow.com/questions/5694319/how-random-is-phps-shuffle-function) $cards = array_merge($cards, array_slice($rare, 0, 16)); $cards = array_merge($cards, array_slice($superrare, 0, 2)); // shuffle everything one more time since cards have been added randomly // to the deck shuffle($cards); // now when we have everything in $cards - 180 of random cards, we can // pack them $pack1 = array_slice($cards, 0, 90); $pack2 = array_slice($cards, 90, 90); // always picking first n cards because they are all shuffled $player1Drafted = array_slice($pack1, 0, 48); $player2Drafted = array_slice($pack2, 0, 48); // print it all print_r(array('Player1' => $player1Drafted, 'Player2' => $player2Drafted));

具有不会修改历史记录的参数_skipLocationChange 这些可以解决问题:

router.navigateByUrl(url: string, _skipLocationChange?: boolean) : Promise<any> router.navigateByUrl('/404', true);

答案 2 :(得分:3)

从Angular 2决赛开始,这就是解决方案:

this._router.navigateByUrl('/404', { skipLocationChange: true })

答案 3 :(得分:0)

这是一个非常有趣的问题,也许您应该将其报告为功能请求。我很高兴能够在RouteDefinition的loader回调中访问路由器指令。

您可以尝试模拟验证添加默认路由/**并使用RouteDefinition的regex参数仅匹配正数。

相关问题