如何获取$ http响应并使用服务分配给本地变量?

时间:2017-06-05 07:22:09

标签: angularjs

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');并将response.data分配给service.js

中的局部变量tableData

3 个答案:

答案 0 :(得分:2)

试试这个:

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;
    });
}

答案 1 :(得分:0)

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

  

$ http.get( 'http://localhost:500/api/studentList')。然后(函数(RES){   tableService.tableData = res; });

有很多方法可以绑定它们。这取决于你如何操纵你的代码。

答案 2 :(得分:0)

首先创建服务

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() {
    });
   }
}
相关问题