如何获得$ HTTP响应并使用服务分配给本地变量



service.js

     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);
  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}

我想打电话给$ http.get('http://localhost:5000/api/studentsList'(;并将响应分配给service.js

中的局部变量tabledata

尝试以下:

angular.module('app')
        .service('tableService', [
        '$q','$http',
      tableService
  ]);
  function tableService($q, $http){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
    $http.get('http://localhost:5000/api/studentsList').then(function(result){
      tableData.data = result.data;
    });
}

您必须将服务中的变量绑定到控制器。

$ http.get('http://localhost:500/api/studentList'(。然后(function(res({ TableService.tabledata = res;}(;

有很多绑定它们的方法。您如何操纵您的代码确实取决于您。

首先创建服务

angular
  .module('app')
  .factory('tableService', tableService);
function tableService($q, $http, $cookies) {
  return {
    tableData: tableData
  };
  function tableData() {
    var d = $q.defer();
    $http({
      method: 'GET',
      url: 'http://localhost:5000/api/studentsList'
    }).success(function(response) {
      d.resolve(response);
    }).error(function(response) {
      d.reject(response);
    });
    return d.promise;
  }
}

注意:我创建了工厂,您也可以通过服务来完成

创建控制器并在控制器中调用服务

angular
  .module('app')
  .controller('tableController', tableController);
function tableController($scope, tableService) {
  $scope.tableData = [];
  tableData();
function tableData() {
    tableService.tableData().then(function(response) {
        if (response.success) {
          $scope.tableData = response.data;
        }
    }, function() {
    });
   }
}

相关内容