Imagine the following AngularJS application:
The idea behind the “doWork” function of the service is to execute some asynchronous code and return a promise to be able to perform some actions once this code has been completed. For the sake of this example, we just wait for 2 seconds and half and resolve the promise by passing an array as the result.
The component has a “counter” variable defined in the “$onInit” method once the promise is resolved.
Even though this code seems correct, if you execute it, you’ll notice that the displayed value never gets updated even though the promise gets resolved after 2 500 milliseconds.
This comes from the fact that the default “Promise” implementation won’t execute the callback in the digest loop of AngularJS, so even though this callback is executed, AngularJS will not notice it so the view won’t get refreshed.
You can fix that issue by simply defining the following “run” function (you have to call it on the value returned by “angular.module”).
This function overrides the default “Promise” implementation by the one of AngularJS (“$q”), meaning that writing:
Is actually equivalent to:
If you run your application, you’ll see that now, the view gets updated once the promise is resolved.