【问题标题】:Unable to consume an Angular service from a Controller无法从控制器使用 Angular 服务
【发布时间】:2014-03-12 21:05:56
【问题描述】:

因此,我进行了广泛的研究并阅读了许多教程,但我无法找到我想要完成的任务的直接答案。

我只是尝试访问存储在 JSON-Generator.com 中的 JSON 对象并将其粘贴在表中并重复它。听起来很简单,但似乎有很多不同的方法可以做到这一点,并且所有来源都遗漏了我需要的一条信息。

如果我在控制器中 console.log eventsService 它返回一个构造函数,如果我 console.log eventsService.data 它返回未定义。

如何在我的控制器中访问从 $http 返回的数据?

// CONTROLLERS


app.controller('currentTradeshowsController', ['$scope', 'eventsService', function($scope, eventsService){


  $scope.events = eventsService.data;


}]);


    // SERVICES


app.service('eventsService',function($http){

  var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';


  $http({method: 'GET', url: eventsUrl}).
    success(function(data){
      // not sure what to write here....
      return data;

    })

    .error(function(){
      console.log('ah shit');
    })



});

【问题讨论】:

  • 您的应用程序代码是否来自 JSON-Generator.com?如果没有,那么您可能会遇到浏览器的跨域限制。您需要进行 JSONP 调用而不是 get 调用。
  • 你没有从服务中返回任何东西,这就是问题
  • 我相信 JSON-Generator 会以某种方式执行 JSONP。在这方面没有问题。

标签: ajax json angularjs


【解决方案1】:

首先,$http 调用是异步的,因此您可能希望使用 Promise 将数据正确加载到作用域变量中

第二 - 你需要从服务中返回一些东西,使它在服务声明函数之外工作

控制器

app.controller('currentTradeshowsController', function($scope, eventsService){
    eventsService.getData().then(function(data) {
        $scope.events = data;
    });
});

服务

app.service('eventsService',function($http){
    var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';

    return {
        getData: function() {
            return $http.get(eventsUrl);
        }
    }
});

$http.get 是 GET 请求的简写,它返回一个 Promise,因此您可以在控制器中简单地使用它与 .then

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多