0

So in my angularJS program, I'm trying to retrieve data from the database and I do so successfully but then lose the value of my variable. Why is this and how can I fix this?

    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);
    }

i'm trying to then call use my locOptions to use my html:

<div ng-repeat="loc in vm.locOptions">...</div>

here's my controller that as well:

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"
});
rcarcia02
  • 927
  • 4
  • 15
  • 46
  • 2
    Because the call to `locTaskOptionsReq.requestLocTaskOptions` is asynchronous and your `console.log(vm.locOptions);` line is hit before the promise resolves. – Lex Jun 01 '18 at 19:26
  • @Lex ah okay, that makes sense. how can I fix that? – rcarcia02 Jun 01 '18 at 19:32
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Jun 01 '18 at 19:36
  • 1
    @MikeMcCaughan, probably not since the OP is using a promise. The promise hasnt resolved yet which fills in the value of vm.locOptionsLoaded. Once the promise resolves, the value will be filled in. – Esaith Jun 01 '18 at 19:46
  • 1
    @Esaith Did you read that question and its answers? It talks about exactly that. – Heretic Monkey Jun 01 '18 at 19:48
  • Yes, you are right. Sorry for skimming it too quickly > – Esaith Jun 01 '18 at 19:49
  • You can get rid of the `ng-if` because if the collection you are iterating with `ng-repeat` is empty it won't output anything. Is that not working for you? Show how `vm` is initialized in your controller as well as your `ng-controller` directive from the view/route/whatever. – Lex Jun 01 '18 at 20:03
  • @Lex I updated it – rcarcia02 Jun 01 '18 at 20:09
  • So at the top of your controller you have `var vm = this;`? Also, `vm.locOptions` looks like an object, not an array. If you are trying to loop the key/value pairs of the object in your `ng-repeat` you'll need to use something like `ng-repeat="(key,value) in vm.locOptions"`. – Lex Jun 01 '18 at 20:16
  • @Lex i do have that at the top of my controller. and oh okay, how would that work with my ng-switch then? – rcarcia02 Jun 01 '18 at 20:43
  • You don't have an `ng-switch` in your question. There are lots of examples of looping an object's properties using `(key,value)` in an `ng-repeat`. Try some and then update your question if you still can't figure it out. – Lex Jun 01 '18 at 20:47

1 Answers1

3

What is happening that your service call requestLocTaskOptions is async calls which means it doesn't stop the thread execution. So it will continue and executes

console.log(vm.locOptions); // Which is null currently as your callback is not executed yet

After the results is retrieved your then callback is executed and vm.locOptions will be set.

So your required code/ business must be included inside the Then Call back or you can create watcher on the vm.locOptions to be executed on value change.

Hany Habib
  • 1,377
  • 1
  • 10
  • 19
  • I've updated my question with my html and since I have an ng-if, shouldn't that work? – rcarcia02 Jun 01 '18 at 19:42
  • if vm.locOptions is init as [] your ng-if will always give you true, you can use better vm.locOptions.length, after your then callback apply cycle will run which will update your view – Hany Habib Jun 01 '18 at 19:45
  • @HanyHabib, what if initialized with a value of 1, then after the promise returns its a difficult value but still length of one? The OP could splice(0) the array if such a circumstance exists. – Esaith Jun 01 '18 at 19:47
  • Esaith you have valid point but why to Initialize array declaration with value 1? i feel that is not valid scenario in this case. – Hany Habib Jun 01 '18 at 19:50
  • @HanyHabib no. but when I console.log the length of vm.locOptions it says undefined – rcarcia02 Jun 01 '18 at 19:58
  • can you provide the code on plunkr and i will update it for you? because it seems maybe you have other binding issue – Hany Habib Jun 01 '18 at 19:59
  • do you have this line of code at the beginning of your controller? var vm = this; – Hany Habib Jun 02 '18 at 07:30