在 AngularJS $routeProvider resolve 中引用路由参数
Referencing route param in AngularJS $routeProvider resolve
我试图在 $routeProvider 路由的解析方法中使用路由参数。这是我的代码:
.when('/agency/edit/:agencyId',
{
controller: 'agencyController',
templateUrl: baseUrl + 'Content/templates/agencyUpsert.html',
resolve: {
agency: ['$routeParams', 'agencyService', function ($routeParams, agencyService) {
return agencyService.getAgency($routeParams.agencyId);
}]
}
})
如您所见,我正在尝试通过 $routeParams.agencyId
访问它,但我也尝试直接 agencyId
(希望它在路由的内容中可用),但它是未定义。
怎样才能引用成功?
您应该使用 $route
而不是 $routeParams
来引用它,如下所示:
.when('/agency/edit/:agencyId',
{
controller: 'agencyController',
templateUrl: baseUrl + 'Content/templates/agencyUpsert.html',
resolve: {
agency: ['$route', 'agencyService', function ($route, agencyService) {
return agencyService.getAgency($route.current.params.agencyId);
}]
}
})
来自docs:
Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.
我试图在 $routeProvider 路由的解析方法中使用路由参数。这是我的代码:
.when('/agency/edit/:agencyId',
{
controller: 'agencyController',
templateUrl: baseUrl + 'Content/templates/agencyUpsert.html',
resolve: {
agency: ['$routeParams', 'agencyService', function ($routeParams, agencyService) {
return agencyService.getAgency($routeParams.agencyId);
}]
}
})
如您所见,我正在尝试通过 $routeParams.agencyId
访问它,但我也尝试直接 agencyId
(希望它在路由的内容中可用),但它是未定义。
怎样才能引用成功?
您应该使用 $route
而不是 $routeParams
来引用它,如下所示:
.when('/agency/edit/:agencyId',
{
controller: 'agencyController',
templateUrl: baseUrl + 'Content/templates/agencyUpsert.html',
resolve: {
agency: ['$route', 'agencyService', function ($route, agencyService) {
return agencyService.getAgency($route.current.params.agencyId);
}]
}
})
来自docs:
Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.