0

I have this code in my controller

 dashboardFactory.totalCustomer().then(function (response){
    $scope.totalCustomer = response.data.count;
  }, function (error) {
    console.log(error);
  });

 dashboardFactory.totalPartner().then(function (response){
    $scope.totalPartner = response.data.count;
  }, function (error) {
    console.log(error);
  });


//below passed to html
$scope.charts = [{
  color: pieColor,
  description: 'Total Partner',
  stats: $scope.totalPartner,
  icon: 'person',
}, {
  color: pieColor,
  description: 'Jumlah Konsumen',
  stats: $scope.totalCustomer,
  icon: 'money',
}];

The above code result in empty, this is because $scope.charts created while promise not yet resolved?

How I can create array of object from promise result if every object have property which get from different promise factory method? so the rendered page is not empty.

The above example is 2 object, imagine if I have 10 or more object each object get from different promise factory method.

Any explanation appreciated as I'm new in angular.

2
  • regardless of how many chart objects are there in the array. is the index of each of the object fixed or they can change? Commented Dec 7, 2016 at 23:06
  • @Sagi_Avinash_Varma doesn't matter because chart object will rendered with ng-repeat :D thanks for comment. Commented Dec 7, 2016 at 23:07

1 Answer 1

1

Use $q.all():

var totalCustomerPromise = dashboardFactory.totalCustomer().then(function (response){
  return response.data.count;
});

var totalPartnerPromise = dashboardFactory.totalPartner().then(function (response){
  return response.data.count;
});

$q.all({
  totalCustomer: totalCustomerPromise,
  totalPartner: totalPartnerPromise
}).then(function(result) {
  $scope.charts = [{
    color: pieColor,
    description: 'Total Partner',
    stats: result.totalPartner,
    icon: 'person',
  }, 
  {
    color: pieColor,
    description: 'Jumlah Konsumen',
    stats: result.totalCustomer,
    icon: 'money',
  }];
});

Or, if you don't care that your objects in the scope don't have a vaid stats until the promises are resolved, just initialize their stats property from within the callbacks passed to then():

dashboardFactory.totalCustomer().then(function (response){
  $scope.charts[1].stats = response.data.count;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.