我如何在不注入 $routeParams 或 $location 的情况下获取 routeParams、路径和搜索的值?
How am I getting values for routeParams, path and search without injecting $routeParams or $location?
请查看下面的示例代码:
var app = angular.module("sampleroute", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "main.htm",
controller: "mainCtrl"
})
.when("/page/:type", {
redirectTo: function (routeParams, path, search) {
console.log(routeParams);
console.log(path);
console.log(search);
return "/";
}
})
.otherwise({
redirectTo:"/"
});
//console.log(routeParams, path, search);
});
以下代码在路由到“/page/types?test=testValue”时打印出 routeParams、path 和 search 的 3 个值。所以这没有任何问题。
我的问题是没有注入 $routeParams
,我得到的是 routeParams
的值,没有注入 $location
我得到的是 path
和 [=15] 的值=].
这是怎么回事?
查看 angular 文档,它指出:
If redirectTo is a function, it will be called with the following
parameters:
{Object.} - route parameters extracted from the current
$location.path() by applying the current route templateUrl.
{string} -current $location.path()
{Object} - current $location.search()
Angular 正在幕后为您做这件事。这就是为什么您不需要直接注入 $location 或 $routeParams 的原因。
这是文档的 link:https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
请查看下面的示例代码:
var app = angular.module("sampleroute", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "main.htm",
controller: "mainCtrl"
})
.when("/page/:type", {
redirectTo: function (routeParams, path, search) {
console.log(routeParams);
console.log(path);
console.log(search);
return "/";
}
})
.otherwise({
redirectTo:"/"
});
//console.log(routeParams, path, search);
});
以下代码在路由到“/page/types?test=testValue”时打印出 routeParams、path 和 search 的 3 个值。所以这没有任何问题。
我的问题是没有注入 $routeParams
,我得到的是 routeParams
的值,没有注入 $location
我得到的是 path
和 [=15] 的值=].
这是怎么回事?
查看 angular 文档,它指出:
If redirectTo is a function, it will be called with the following parameters:
{Object.} - route parameters extracted from the current $location.path() by applying the current route templateUrl.
{string} -current $location.path()
{Object} - current $location.search()
Angular 正在幕后为您做这件事。这就是为什么您不需要直接注入 $location 或 $routeParams 的原因。
这是文档的 link:https://docs.angularjs.org/api/ngRoute/provider/$routeProvider