【问题标题】:angularJS service not getting calledangularJS服务没有被调用
【发布时间】:2015-01-22 08:05:18
【问题描述】:

我对 AngilarJS 很陌生。我正在尝试用 angularJS 编写服务。

<script>
var module = angular.module("myapp", []);

module.service('BrandService', function ($http) {

    var brands = [];

    this.getBrands = function()
    {
        return $http.get('http://admin.localhost/cgi-bin/brand.pl')
            .then(function(response) 
            {
                brands = response.brands;
                alert (brands);
            });
    }

    //simply returns the brands list
    this.list = function () 
    {
        return brands;
    }


});

module.controller("brandsController", function($scope, BrandService) {
    $scope.brandlist = BrandService.list();
    alert ($scope.brandlist);
});

</script>

声明“警报(品牌);”没有被调用。这段代码有什么问题。 m 在实现中是否遗漏了任何东西?

【问题讨论】:

  • 警报为空还是不警报?
  • 服务中不提示,控制器中提示为空。
  • 打开调试控制台,告诉我们错误信息是什么。
  • 您的控制器是否在某处被调用? (例如在 ng-controller 指令中)
  • 您可以尝试将 $window 注入服务并调用 $window.alert 而不是 alert 吗?

标签: angularjs


【解决方案1】:

$http 调用始终是异步的。这意味着,即使您在服务中使用.then,它也无法将解析的数据正确地返回到您的控制器中。您必须在控制器中编写它。

您的服务:

module.service('BrandService', function($http) {
  var brands = [];
  this.getBrands = function() {
    //do not need the dot then.
    return $http.get('http://admin.localhost/cgi-bin/brand.pl')
  }
  //simply returns the brands list
  this.list = function() {
    return brands;
  }
});

在您的控制器中:

module.controller("brandsController", function($scope, BrandService) {
  BrandService.list()
    .then(function(response) {
      $scope.brandlist = response.brands;
      alert($scope.brandlist);
    });
});

【讨论】:

    【解决方案2】:

    在役:

    this.getBrands = function() {
      $http.get('http://admin.localhost/cgi-bin/brand.pl').then(function(response) {
        brands = response.brands;
        alert(brands);
        return brands;
      });
    }
    

    在控制器中:

       $scope.brandlist = BrandService.getBrands();
    alert($scope.brandlist);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-27
      • 2016-03-09
      • 2014-07-31
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多