从 Angular 从 ng-ressource 获得的 JS Promise 读取数据

Read Data From Angular JS Promise Got From ng-ressource

我正在尝试读取在我编写

时可以在控制台中看到的以下字段 (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';
    }
  };

}]);

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;

$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 传递给查询参数。