【发布时间】:2013-12-13 00:38:04
【问题描述】:
在我正在开发的 Angular 应用程序中,我希望有一个抽象父状态,它必须解决其所有子状态的某些依赖关系。具体来说,我希望所有需要经过身份验证的用户从某个 authroot 状态继承该依赖项的状态。
我遇到了父依赖项并不总是被重新解决的问题。理想情况下,我想让父状态检查用户是否仍然自动登录任何子状态。在docs 中,它说
子状态将从父状态继承已解决的依赖关系,它们可以覆盖这些依赖关系。
我发现只有当我从父状态之外的状态进入任何子状态时才会重新解决父依赖关系,但如果在兄弟状态之间移动则不会。
在这个例子中,如果你在 authroot.testA 和 authroot.testB 状态之间移动,GetUser 方法只会被调用一次。当您移动到other 状态并返回时,它将再次运行。
我可以将 User 依赖项放在每个子状态上,以确保每次进入这些状态时都会调用该方法,但这似乎违背了继承依赖项的目的。
我对文档的理解有误吗?有没有办法强制父状态重新解析其依赖关系,即使兄弟之间的状态发生变化?
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.0/angular-ui-router.min.js"></script>
<script>
(function(ng) {
var app = ng.module("Test", ["ui.router"]);
app.config(["$stateProvider", "$urlRouterProvider", function(sp, urp) {
urp.otherwise("/testA");
sp.state("authroot", {
abstract: true,
url: "",
template: "<div ui-view></div>",
resolve: {User: ["UserService", function(UserService) {
console.log("Resolving dependency...");
return UserService.GetUser();
}]}
});
sp.state("authroot.testA", {
url: "/testA",
template: "<h1>Test A {{User|json}}</h1>",
controller: "TestCtrl"
});
sp.state("authroot.testB", {
url: "/testB",
template: "<h1>Test B {{User|json}}</h1>",
controller: "TestCtrl"
});
sp.state("other", {
url: "/other",
template: "<h1>Other</h1>",
});
}]);
app.controller("TestCtrl", ["$scope", "User", function($scope, User) {$scope.User = User;}]);
app.factory("UserService", ["$q", "$timeout", function($q, $timeout) {
function GetUser() {
console.log("Getting User information from server...");
var d = $q.defer();
$timeout(function(){
console.log("Got User info.");
d.resolve({UserName:"JohnDoe1", OtherData: "asdf"});
}, 500);
return d.promise;
};
return {
GetUser: GetUser
};
}]);
})(window.angular);
</script>
</head>
<body ng-app="Test">
<a ui-sref="authroot.testA">Goto A</a>
<a ui-sref="authroot.testB">Goto B</a>
<a ui-sref="other">Goto Other</a>
<div ui-view>Loading...</div>
</body>
</html>
【问题讨论】:
标签: angularjs angular-ui-router