Question

In the first sample code all works as should - on every page route change we check some conditions ($timeout) and resolve a promise:

JSFiddle Var sample code

In the second sample we move var rulesFactory to app.factory('rulesFactory') and now it works once:

JSFiddle App Factory sample code

Is it cache? How to solve this to improve code reusabilty?

Was it helpful?

Solution

The code in your rulesFactory was only ever running once - the first time the service itself was instantiated.

It does this on resolve the first time:

  1. Angular sees it's looking for something to inject called 'rulesFactory'
  2. Angular finds a service called rulesFactory. It sees no one has used rulesFactory yet, and instantiates the service.
  3. The service rulesFactory is instantiated, and the $timeout is run with a promise returned

It does this on resolve the second time:

  1. Angular sees it's looking for 'rulesFactory'. rulesFactory already exists!
  2. Angular just gets the existing object for rulesFactory.
  3. The timeout has already run out from earlier, and the same already resolved promise will be used.

The fix for this is to have the rulesFactory return a function which will run the timeout again - every time you want it.

And additionally, $timeout itself returns a promise, so you can just return a $timeout :-)

http://jsfiddle.net/JbTkp/4/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top