Search code examples
angularjsangular-resource

How to get `$promise.then` value by return in the `$resource`?


From one of the service, I am retuning a back-end output. I am getting values, but how to get the result values from the returned object?

here is my code :

var queryConractorInfo = function ( server, contractorParams ) {

            return server.contractorInfo.get(contractorParams)
                  .$promise.then(function ( contractorInfo ) {

                    return contractorInfo;

            })

}

here is my call :

console.log( queryConractorInfo( server, contractorParams) );

here is the output I am getting :

{
  "$$state": {
    "status": 1,
    "value": { // i want to get this from returned object.
      "ActualPercentage": "33.5",
      "AllWeeks": [
        "/Date(1446930000000+0300)/",
        "/Date(1446498000000+0300)/",
        "/Date(1439154000000+0300)/",
        "/Date(1438635600000+0300)/",
        "/Date(1436043600000+0300)/",
        "/Date(1431550800000+0300)/",
        "/Date(1389733200000+0300)/",
        "/Date(1332277200000+0300)/"
      ]
}
}
}

I tried like this:

var queryConractorInfo = function ( server, contractorParams ) {

            return server.contractorInfo.get(contractorParams)
                  .$promise.then(function ( contractorInfo ) {

                    return contractorInfo.promise;
                    //adding promise but not working

            })

}

Solution

  • As I understood your case, you seem to be stuck on returning something.

    That's not how it works with promises. Returning from a promise callback (or resolve function) will only pass data to the next .then() function. You can chain many then-calls

    var queryContractorInfo = function ( server, contractorParams ) {
    
        return server.contractorInfo.get(contractorParams)
            .$promise.then(function ( contractorInfo ) {
    
                // This will return to the next .then() call
                return contractorInfo;
            })
            .then(function(contractorInfo) {
    
                // Another then call, understand?
            });
    }
    

    It basicly works like this

    // Outer variable, initialized to null (use an empty object if you prefer)
    var queryContractorInfo = null;
    
    server.contractorInfo.get(contractorParams)
        .$promise.then(function ( contractorInfo ) {
    
            // Now I can set queryContractorInfo
            queryContractorInfo = contractorInfo;
    
            // You can return, but you don't need to, if this is the final then
        });
    

    The queryContractorInfo is empty, as long as the query is in progress. When you get a result, the variable is set to the result data. In the then function you could now trigger further functions, if you want to work with this variable.