简体   繁体   中英

AngularJS promise resolution not updating GUI until next user interaction

I am using an Angular2-style component in AngularJS. In my component, I have a function that is meant to update the GUI by changing the options of a dropdown:

    var ctrl = this;
    async function updateOptions(node) {
          var name = node.name;
          let result = await MyService.getResult(name);
          ctrl.options = result;
          console.log(ctrl.options); 
    }

The corresponding HTML to display those options is:

  <select ng-if="$ctrl.getType() === 'dropdown'"
    class="form-control selectList"
    ng-model="$ctrl.value"
    ng-options="option.key as option.displayName for option in $ctrl.options">
  </select>

where getType() always returns 'dropdown' .

The dropdown starts blank. The user selects an option from the dropdown. The console logs the options and the dropdown updates correctly. The user selects ANOTHER option from the dropdown. The console logs the options correctly AGAIN. But THIS time, the dropdown does NOT update. All subsequent times, the dropdown shows the options of the PREVIOUS thing the user selected.

Looking forward to some good detective work. Happy to provide more snippets of code from this large project. I'm wondering if this could be an issue with the way that AngularJS updates.

UPDATE:

MyService code:

this.getResult = function(name) {
  return myFactory.getStuff(name).then(
    function(response) {
      return response.result.map(...);
    }
  );
};

MyFactory code:

myFactory.getStuff = function(name) {
  return $http.get('/url/here/' + name)).then(
      function(response) {
        return response.data;
      }
    );
};

await is meant for native promises which are supported by the browser. You can also use .then syntax on native promises.

But AngularJS uses its own promises that come from $q service. Thus you are required to use .then syntax because the browser doesn't know about these promises.

When you use promises from the $q service (eg when you use $http ) you don't have to worry about digest cycles because a digest is run for you when the promise is fulfilled. But if you use native promises in AngularJS, you usually have to run a digest cycle manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM