所以在我的angularJS程序中,我正在尝试从数据库中检索数据,并且我成功地这样做了,但后来失去了变量的值。为什么会这样,我该如何解决这个问题?
function loadLocOptions() {
locTaskOptionsReq.requestLocTaskOptions(vm.task).then(function (data) {
if (data == null) {
vm.locOptions = locTaskOptionsService.getEmptylocTaskOption();
vm.locOptions.ERPKey = sessionService.getCurrentUser().ERPKey;
vm.locOptions.LocKey = sessionService.getCurrentUser().LocKey;
} else {
vm.locOptions = data;
}
vm.locOptionsLoaded = true;
// Data is here
console.log(vm.locOptions);
});
// Now is null
console.log(vm.locOptions);
}
我正在尝试使用我的locOptions
来使用我的html:
<div ng-repeat="loc in vm.locOptions">...</div>
这里也是我的控制器:
module.component("asaLocOptionsComponent", {
bindings: { task: '='},
controllerAs: "vm",
controller: ["$scope", "$location", "shellPageAdapter", "sessionService", "staticData", "activeData", "ScreenModes", "localizationService", "locationReq", "locTaskOptionsService", "locTaskOptionsReq", asaLocOptionsController],
transclude: false,
templateUrl: "/system/SystemManager/app/organization/asaLocOptions.html"
});
答案 0 :(得分:3)
您的服务调用requestLocTaskOptions是异步调用会发生什么,这意味着它不会停止线程执行。所以它会继续并执行
console.log(vm.locOptions); // Which is null currently as your callback is not executed yet
检索结果后,执行回调并设置vm.locOptions。
因此,您所需的代码/业务必须包含在Then Call中,或者您可以在vm.locOptions上创建观察者,以便在值更改时执行。