如何在 运行 方法中访问控制器的变量
how to access variable of controller in the run method
在我的项目中,当用户来自任何 url 时,首先我会在控制器中检查用户的最后状态是什么,如果他们进入尚无法访问的页面,然后我设置一个 $rootScope 变量到用户的当前状态,并在应用程序的 运行 方法中使用这个变量,并根据我在控制器中设置的 $rootScope 中的当前状态将它们发送到状态,但我的问题是函数正在从nodejs的api获取当前状态在运行方法中检查应用后调用,所以结果在运行方法中显示未定义的当前状态,因为控制器功能是运行ning 在 运行 方法的代码之后。我无法理解如何解决这个问题。拜托,我请求你帮我解决这个问题。
Here is the code of the function of the controller which set the $rootScope variable
$scope.getUserDetails = function () {
appService.getDetails('/user/getDetails').then(function (response) {
$scope.current_status = response.current_status;
$rootScope.current_status = $scope.current_status;
}
}
And here is the code of run method
if (transition.to().name == "user.stateName"){
console.log($rootScope.current_status);
$state.go('store.' + $rootScope.current_status);
}
Output of the $rootScope.current_status in console is
undefined
run
函数将在控制器实例化之前执行。这就是为什么尝试获取 run
中的变量将产生 undefined
.
您可以改为在状态配置中使用 redirectTo
以根据某些逻辑重定向到特定状态。
.state('user.stateName', {
...
redirectTo: function(transition) {
var service = transition.injector().get('appService')
return service.getDetails('/user/getDetails')
.then(function(response) {
return response.current_status;
});
}
})
经过大量搜索终于解决了我的问题,当我在运行方法中注入appService并调用appService方法时,我的问题就解决了。
在我的项目中,当用户来自任何 url 时,首先我会在控制器中检查用户的最后状态是什么,如果他们进入尚无法访问的页面,然后我设置一个 $rootScope 变量到用户的当前状态,并在应用程序的 运行 方法中使用这个变量,并根据我在控制器中设置的 $rootScope 中的当前状态将它们发送到状态,但我的问题是函数正在从nodejs的api获取当前状态在运行方法中检查应用后调用,所以结果在运行方法中显示未定义的当前状态,因为控制器功能是运行ning 在 运行 方法的代码之后。我无法理解如何解决这个问题。拜托,我请求你帮我解决这个问题。
Here is the code of the function of the controller which set the $rootScope variable
$scope.getUserDetails = function () {
appService.getDetails('/user/getDetails').then(function (response) {
$scope.current_status = response.current_status;
$rootScope.current_status = $scope.current_status;
}
}
And here is the code of run method
if (transition.to().name == "user.stateName"){
console.log($rootScope.current_status);
$state.go('store.' + $rootScope.current_status);
}
Output of the $rootScope.current_status in console is
undefined
run
函数将在控制器实例化之前执行。这就是为什么尝试获取 run
中的变量将产生 undefined
.
您可以改为在状态配置中使用 redirectTo
以根据某些逻辑重定向到特定状态。
.state('user.stateName', {
...
redirectTo: function(transition) {
var service = transition.injector().get('appService')
return service.getDetails('/user/getDetails')
.then(function(response) {
return response.current_status;
});
}
})
经过大量搜索终于解决了我的问题,当我在运行方法中注入appService并调用appService方法时,我的问题就解决了。