读取Angular JS承诺的数据来自ng-ressource

时间:2016-03-12 23:29:53

标签: angularjs node.js angular-resource

我正在尝试阅读以下字段(LocationID ..),我在编写时可以在控制台中看到

console.log($scope.businessInformation);

Console photo capture

你能帮我吗?

由于

的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';
    }
  };

}]);

路由/ 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;

1 个答案:

答案 0 :(得分:0)

$ resource很棒,因为当您调用query之类的操作时,您收到的对象将在promise解析后立即自动填充。这里的问题是你在诺言解决之前尝试在调用它之后立即记录它。

如果您想在控制器中使用它,可以将代码添加到承诺中,该承诺是属性$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);
  });
};

如果您想在视图中使用它,可以使用$resolved参数来了解数据是否已准备就绪。

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

我还想指出在查询运行之前使用$scope.businessInformation的奇怪之处。您将$scope.businessInformation.industryId传递给查询参数。