Search code examples
angularjsnode.jsangular-resource

Read Data From Angular JS Promise Got From ng-ressource


I'm trying to read the following fields (LocationID ..) that I can see in the console when I wrote

console.log($scope.businessInformation);

Console photo capture

Can you help me please?

Thanks

Script.js

app.controller('ProfileController', ['$scope', function($scope) {
  $scope.dropLink = '1';
  $scope.dropContentLink = '1';

}]);

app.factory('infoService', ['$resource', function($resource){
  return $resource('/api/business-information/:id');
}]);

app.controller('BusinessInfoController', ['$scope', 'infoService', function($scope, infoService) { 

  $scope.isActive = 1;
  $scope.is_active_label = 'Active';

  $scope.getInfo = function() {

      $scope.businessInformation = infoService.query({id: $scope.businessInformation.industryID});
      console.log($scope.businessInformation);
  };

  $scope.updateLabel = function(){
    if($scope.isActive === 1){
      $scope.is_active_label = 'Active';
    }else {
      $scope.is_active_label = 'Not Active';
    }
  };

}]);

routes/api.js

router.route('/business-information/:id')

    .get(function(req, res){

        conn.query('CALL Inductry_Location_Get(?)', [req.params.id],function(err,info){

          if(err) res.send(err); 
          console.log('Data received from Db:\n');
          console.log(info[0]);
          return res.send(info);
        });
    }) ;

module.exports = router;

Solution

  • $resource is awesome because when you call an action like query, the object you receive back will be auto populated as soon as the promise resolves. The problem here is you try to log it right after calling it before the promise gets resolved.

    If you want to use it from your controller, you can add your code to the promise which is a property $promise

    $scope.getInfo = function() {
      $scope.businessInformation = infoService.query({
        id: $scope.businessInformation.industryID
      });
    
      $scope.businessInformation.$promise.then(function(data) {
        // Access data parameter or
        console.log(data);
        // Use $scope.businessInformation directly since its populated at this point
        console.log($scope.businessInformation);
      });
    };
    

    If you are wanting to use it on your view, you can use the $resolved parameter to know if the data is ready yet.

    <div ng-show="businessInformation.$resolved">{{ businessInformation }}</div>
    

    I also want to point out an oddity which is you using $scope.businessInformation before the query is even run. You pass $scope.businessInformation.industryId into the query params.