0

In an ASP.NET Boilerplate project, I have the following code:

(function () {
    appModule.controller('augustinum.views.kostenstelle.index', [
        '$scope', '$uibModal', 'abp.services.app.kostenstelle',
        function ($scope, kostenstelleService) {
            var vm = this;

            vm.kostenstellen = [];

            vm.getKostenstelle = function () {
                kostenstelleService.getKostenstelle().then(function (result) {
                    vm.kostenstellen = result.items;
                    console.log("Step1" + vm.kostenstellen.length);
                });
            };

            vm.getKostenstelle();   
            console.log("Step2" + vm.kostenstellen.length);
        }
    ]);
})();

I have two questions:

  1. I get the error:

    getKostenstelle() is not a function.

    If I replace kostenstelleService.getKostenstelle() with abp.services.app.kostenstelle.getKostenstelle() the code works — the object list Kostenstelle is returned. But I think I lost the scope with this workaround, so what is wrong with the kostenstelleService?

  2. If the code works (by replacing kostnestelleService), I get 2 elements in the array kostenstelle[]. At the line with "Step1" I get the correct number — 2 elements. But at the line with "Step2", I get 0 elements. Why? And how can I change the code, so the line with "Step2" is executed when the array is filled?

Many thanks in advance.

aaron
  • 39,695
  • 6
  • 46
  • 102
Cellardoor
  • 11
  • 1

1 Answers1

0

1) That's because you forgot to include $uibModal in here function ($scope, kostenstelleService) { (line 4). Therefore kostenstelleService points at $uibModal now.

Should be:

appModule.controller('augustinum.views.kostenstelle.index', 
    ['$scope', '$uibModal', 'abp.services.app.kostenstelle',
    function ($scope, $uibModal, kostenstelleService) {

2) That's because getKostenstelle() is an asynchronous operation wrapped in a promise. JavaScript is single threaded, meaning that it goes through each operation one by one and puts async ops in the pending queue so that it doesn't get thread locked.

In your case, what happens is:

  1. Execute vm.getKostenstelle()
    • Execute kostenstelleService.getKostenstelle() and put in pending queue
  2. Execute console.log("Step2" + vm.kostenstellen.length);
    • At this point vm.kostenstellen.length is empty because the async call hasn't finished
  3. Async call kostenstelleService.getKostenstelle() finishes
    • .then block is executed; vm.kostenstellen is assigned data and console.log("Step1" + vm.kostenstellen.length); displays data
Protozoid
  • 1,207
  • 1
  • 8
  • 16