0

Before a state is loaded, I wish to resolve a factory using the data from another factory.

My situation:

"taskVariables": function (getTask, getTaskVariables, $stateParams) {
      getTask.get({'task': $stateParams.taskId}).success(function(data) {
         console.log("I'm here");
         return getTaskVariables.get({'processInstanceId': data.processInstanceId});
      });
      return false;
      console.log("I have failed you master")
  },

Factory:

.factory('getTask', function ($resource) {
        return $resource('api/task/get/:task', {'user': '@user', 'task': '@task'}, {
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    data = angular.fromJson(data);
                    return data;
                }
            }
        })
    })

The thing is that I think that one factory is loading faster than the other, thus the data will be undefined on page load, but that is just me speculating.

Is there a way to achieve this with maybe a promise or some kind?

Thanks in advance,

Rafael
  • 788
  • 2
  • 17
  • 38

2 Answers2

1

Because I return a $resource I cannot declare a success- nor a failure function, so you need to change it by giving it a $promise, followed by a then:

"taskVariables": function (getTask, getTaskVariables, $stateParams) {
       return getTask.get({'task': $stateParams.taskId}).$promise.then(function(data) {
              return getTaskVariables.get({'processInstanceId': data.processInstanceId});
       });
}

reffering to this question/answer

Community
  • 1
  • 1
Rafael
  • 788
  • 2
  • 17
  • 38
0

You're forgetting to return the initial getTask promise.

"taskVariables": function (getTask, getTaskVariables, $stateParams) {
    return getTask.get({'task': $stateParams.taskId}).success(function(data) {
        console.log("I'm here");
        return getTaskVariables.get({'processInstanceId': data.processInstanceId});
    });
},
Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
  • Thanks for the tip, unfortunately it is not working :( – Rafael Apr 18 '16 at 07:46
  • Reaching the resolving factory, neither the success or the failed state is returned, it is not being logged – Rafael Apr 18 '16 at 07:48
  • Place a [debugger](https://developer.chrome.com/devtools#debugging-javascript) in your code and walk through it, is getTask defined ? is getTask.get a promise ? – Martijn Welker Apr 18 '16 at 07:49
  • 1
    Apologies for not telling you that I use a $resource and not an $http call in my factory. It works now with a $promise, as I found out you cannot have a .success with a $resource – Rafael Apr 18 '16 at 08:52