Siavosh Tehrani
Siavosh Tehrani

Reputation: 135

Updating Json values with a promise

I want to populate some values in Json that are being calculated with angular-promises and these value should be updated after certain events. I tried to call the factory which yields the values for example something like below and tried to call the functions GetWeeklyVal and GetDailyVal which are in charge of calculating the values :

this.salesList = 
    {"sales":[
        {   "id":"A1", "dailyValue": GetDailyVal('A1'), "weeklyValue": GetWeeklyVal('A1')},
        {   "id":"A2", "dailyValue": GetDailyVal('A2'), "weeklyValue": GetWeeklyVal('A2')}
    ]}

and in my controller I have:

$scope.sales= salesServices.salesList.sales;

but it didn't work. the values remain zero which is the default value in the application. Why the values are not being updated and what would be a better solution?

update

This is the portion of the code I call the calculation functions: (I skip the portion to get the values based on passed id in here)

function GetDailyVal(id){
    var dValue = 0;
    salesService.getSales();
    dValue = salesService.totalAmount;
    return dValue;
}

this is the factory

.factory('salesService', ['$http', '$q'],
function salesInvoiceService($http, $q) {

    var service = {
        sales: [],
        getSales: getSales,
        totalAmount: 0
    };
    return service;

    function getSales() {
        var def = $q.defer();
        var url = "http://fooAPI/salesinvoice/SalesInvoices"; //+ OrderDate filter

        $http.get(url)
          .success(function(data) {
            service.sales = data.d.results;
            setTotalAmount(service.sales);
            def.resolve(service.sales);
          })
          .error(function(error){
            def.reject("Failed to get sales");
          })
          .finally(function() {
            return def.promise;
         });
    }

    function setTotalAmount(sales){
        var sum = 0;
        sales.forEach(function (invoice){
            sum += invoice.AmountDC;
        });
        service.totalAmount = sum;
    }
})

Upvotes: 1

Views: 190

Answers (2)

Tarun Dugar
Tarun Dugar

Reputation: 8971

The reason why its not working is:

dailyValue: GetDailyVal('A1')

Here, GetDailyVal makes an async ajax call to an api. For handling async requests, you have to return a promise as follows in your GetDailyVal function as follows:

function GetDailyVal() {
    salesService.getSales().then(function(data) { //promise
        dValue = salesService.totalAmount;
        return dValue;
    })
}

Same thing need to be done for weeklyValue.

Upvotes: 0

Libu Mathew
Libu Mathew

Reputation: 2996

I think there are some errors in your code.

I give some sample code here. I think this will help you.

This is a sample code in one of my application. Check it.

service.factory('Settings', ['$http','$q', function($http,$q) {
    return {
            AcademicYearDetails : function(Details) {
                return $http.post('/api/academic-year-setting', Details)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    return $q.reject(response.data);
                });
            },
            newUser : function(details) {
        return $http.post('/api/new-user', details);
      }

} }]);

Upvotes: 1

Related Questions