setInterval and updating values AngularJS

2019-02-27 21:28发布

问题:

Based on changing the value of a variable I wish to display an error message in my html. I call an api from my angular code, and if it returns an error, I have set up a setInterval function that should update bookingData.tracking_id to false and then show an error message in the html. This should be very easy but combining this with setInterval is proving slightly difficult.

Here is the angular/javascript

this.confirmTrackingTest = function () {
  TestService.finalPackageCheck({tracking_id: controller.bookingData.tracking_id}).$promise.then(function (data) {
    return data;
  }).catch(function (err) {
    var i = 0;
    var interval = setInterval(function () {
      i += 1;
      if (i === 3) {
        if (err.statusText === "Not Found") {
          controller.bookingData.showErrorMessage = true;
        }
        clearInterval(interval)
      }
    }, 2000);
    console.log(controller.bookingData.showErrorMessage)
  });
}

this.bookingData = {
  showErrorMessage: false,
  tracking_id: 1
};

Here is the html:

{{Packs.bookingData.showErrorMessage}}
<div class="alert alert-danger" role="alert" ng-if="Test.bookingData.showErrorMessage">
  <p>Please show this message</p>
</div>

The {{Packs.bookingData.showErrorMessage}} shows false so that is recongised in the html.

Please let me know if any further information is required.

回答1:

This is exactly the reason why the Angular gods invented $interval in order to remove the need to manually use $apply.

So either you call $scope.$apply inside the callback or you use $interval (don't forget to include it in the parameter list for depedency injection)