我有一个“详细” View 和一个使用 id 初始化数据的 Controller 。
我的看法:
<div ng-app="AFApp" ng-controller="AgentCtrl" ng-init="init('@Model.Id')">
我的 Controller :
$scope.id;
$scope.agent = {};
$scope.init = function (id) {
$scope.id = id;
getAgent();
getAgentStatus();
getSystemInfo();
getActions();
};
问题在于方法“getAgentStatus();”在“getAgent();”之前执行。 “getAgentStatus”需要“getAgent”提供的 $scope.agent 数据。函数 getAgentStatus 有一个附加的计时器,它在计时器结束时获取值,但不在 init 函数中获取值。有人可以帮我解决 Angular Controller 中的方法执行顺序以及如何以最佳方式提供 id 参数吗?
参见以下方法:
function getAgent() {
agentDataFactory.getAgent($scope.id)
.success(function (data) {
$scope.agent = data;
})
.error(function (error) {
console.log('Unable to load data: ' + error.message);
});
};
function getAgentStatus() {
if (typeof ($scope.agent.ServiceUrl) == 'undefined' || $scope.agent.ServiceUrl == null) {
console.log('getAgentStatus: ServiceUrl is undefined ' + JSON.stringify($scope.agent));
}
agentDataFactory.getAgentStatus($scope.agent.ServiceUrl)
.success(function (data) {
$scope.agent.CurrentStatus = data.Status;
$scope.agent.CurrentInterval = data.Interval;
})
.error(function (error) {
console.log('Unable to load data: ' + error);
});
$timeout(getAgentStatus, 3000);
};
最佳答案
您可以将 getAgentStatus()
作为回调参数传递给 getAgent()
并在 success
回调中执行它(此时将定义代理
):
function getAgent(callback) {
agentDataFactory.getAgent($scope.id)
.success(function (data) {
$scope.agent = data;
callback && callback();
})
.error(function (error) {
console.log('Unable to load data: ' + error.message);
});
};
$scope.init = function (id) {
$scope.id = id;
getAgent(getAgentStatus);
getSystemInfo();
getActions();
};
简短说明:
首先是一些亮点:
agentDataFactory.getAgent($scope.id).success(...).error(...);
:
异步创建一个 Promise(将被解析)并注册两个回调,一个用于成功解析 Promise,另一个用于发生错误。.success(function (data) { $scope.agent = data; })
:
当 promise 成功解决时注册回调。 当(如果)发生这种情况,$scope.agent
将被设置。function getAgentStatus() { if (typeof ($scope.agent.ServiceUrl...
: 尝试访问$scope.agent
的某些属性,因此需要定义该对象。
那么,您的代码会发生什么:
getAgent()
被调用。
[$scope.agent 未定义]- 创建一个 promise ,当解决时将设置
$scope.agent
。
[$scope.agent 未定义] getAgent()
返回并调用getAgentStatus()
。
[$scope.agent 未定义]getAgentStatus()
尝试访问$scope.agent
的属性但失败。
[$scope.agent 未定义]- 第 2 步中创建的 Promise 已得到解析,并且其
success
回调得到执行。
[$scope.agent 最终定义]
我的代码版本确保在 promise 解决之前不执行getAgentStatus()
,从而定义$scope.agent:
getAgent()
被调用。
[$scope.agent 未定义]- 创建一个 promise ,当解决时将设置
$scope.agent
。
[$scope.agent 未定义] getAgent()
返回并调用其他函数(例如getSystemInfo()
、getActions()
等)。
[$scope.agent 未定义]- 第 2 步中创建的 Promise 已得到解析,并且其
success
回调得到执行。
[$scope.agent 最终定义] - 直到现在,
getAgentStatus()
才会被调用,并且它按预期工作,因为...
[$scope.agent 已定义]
看看$q
service 有关 Angular Promise 的更多信息。
关于asp.net-mvc - AngularJS 服务器端变量到 ng-init 和方法序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21123509/