I have created a state using state provider and i used resolve
, i called api using factory.
.state('Test', {
url: '/Test/:testId',
templateUrl: TEMPLATE_URL + 'Test/test.html',
controller: "testController",
resolve: {
getTest : function($stateParams,TestFactory){
return testFactory.getTest($stateParams.testId);
},
testId: ['$stateParams', function ($stateParams) {
return $stateParams.testId;
}]
}
});
})
I have created a factory having a function(getTest ) which return the object
getTest : function(parmTestId){
var deferred = $q.defer();
$http.get(API_URL + "Test/testById?testId="+parmTestId).success(deferred.resolve)
.error(deferred.resolve);
return deferred.promise;
}
I have created controller, inject provider
.controller("testController", function($scope,$rootScope,$http,getTest,testId, TestFactory ){
console.log(getTest); // its work perfectly and return json object
var returnObj = TestFactory.getTest(testId); //I called factory function
console.log(returnObj)//its not return object its return Promiss
}
I am not able to understans when i call by state resolve, its return json object which is return from api call but when i call in the controller its not retrun json object. Its return
Promise {$$state: Object}
$$state: Object
status: 1
value: Object
__proto__: Object
__proto__: Promise
In the value have the actual result which i want(json object) Question is in both case, why its return different object ?
Thank you in advance. if you dont understand this i will discuss in comment.
It's returning a promise object, which is waiting to be handled!
You may use .then(successCallback, errorCallback)
for the same:
var returnObj = TestFactory.getTest(testId).then(
function(res) {
// The 1st argument passed in this function is the response object
console.log(res);
},
function(err) {
// This is called in case the request fails
console.log('Some error: ', err);
}
);
Also, found the bug in your getTest
method:
$http.get(API_URL + "Test/testById?
testId="+parmTestId).success(function(res) { deferred.resolve(res); })
.error(function(err) { deferred.reject(err); });
return deferred.promise;
deferred.resolve and deferred.reject are methods, so you have to call them!