简体   繁体   English

带有$ http.get的AngularJS服务不会将数据传递给控制器

[英]AngularJS service with $http.get doesn't pass data to a controller

I'm new to AngularJS and still stuck at the basics. 我是AngularJS的新手,仍然停留在基础知识上。

I'm creating a service with a $http.get to load a couple of Json files. 我正在使用$ http.get创建服务来加载几个Json文件。 When I load the service into the controller I get empty arrays. 当我将服务加载到控制器中时,会得到空数组。

This is my service 这是我的服务

app.service('productService', ['$http', function($http){
    var lista = this;
    lista.products = [];
    lista.menu = [];

    $http.get('/prodotti_1.json').success(function(data){
        lista.products = data;
    });

    $http.get('/menu_1.json').success(function(data){
        lista.menu = data;
    });
}]);

And this is my controller: 这是我的控制器:

app.controller('ProductController', ['productService', function(productService){
    console.log(productService.products);
    console.log(productService.menu);
}]);

The console prints just an empty Array [ ]. 控制台仅打印一个空Array []。 If I put the console.log(data) inside the success promise, the console.log prints the array just fine. 如果我将console.log(data)放在成功承诺中,console.log会很好地打印数组。 I thought from codeschool it could be easier, but I guess I'm missing a point to pass the data from the success promise to the controller. 我认为从代码学校开始可能会更容易,但是我想我缺少将数据从成功承诺传递到控制器的要点。 In many other situations I see the usage of $scope variable, but I learnt that I can also avoid the use if I use "this". 在许多其他情况下,我可以看到$ scope变量的用法,但是我了解到,如果我使用“ this”,也可以避免使用该变量。 So that's my code doesn't display any $scope. 这就是我的代码,不显示任何$ scope。

I'm using Angular 1.4.1 FYI and I saw many forums and other questions but it seems a different situation. 我正在使用Angular 1.4.1 FYI,我看到了很多论坛和其他问题,但情况似乎有所不同。

Thank you 谢谢

You are accessing the variables before the promise is resolved. 您在解决诺言之前正在访问变量。 What you can do is return an object that has your various promises as property. 您可以做的是返回一个具有各种诺言作为属性的对象。

app.service('productService', ['$http', function($http){
    return {
         request1: $http.get('/prodotti_1.json'),
         request2: $http.get('/menu_1.json')
       }
}]);

So you can handle it in your controller. 因此,您可以在控制器中处理它。

app.controller('ProductController', ['productService', function(productService){
    productService.request1.success(function(data){
        //access the data
    });

    productService.request2.success(function(data){
        //access the data
    });
}]);

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM