AngularJS应用程序:从JSON一旦加载数据,并在多个控制器使用 [英] AngularJS App: Load data from JSON once and use it in several controllers

查看:231
本文介绍了AngularJS应用程序:从JSON一旦加载数据,并在多个控制器使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AngularJS作为一个框架,一个移动应用程序,目前我有类似这样的结构:

 的app.config(['$ routeProvider',函数($ routeProvider){
    $ routeProvider
        。什么时候('/', {
            templateUrl:'页/ home.html做为',
            控制器:'homeCtrl
        })        。当('/个',{
            templateUrl:'页/ one.html',
            控制器:'oneCtrl
        })        。当('/二',{
            templateUrl:'页/ two.html',
            控制器:'twoCtrl
        });
}]);app.controller('homeCtrl',['$范围',函数($范围){}]);app.controller('oneCtrl',['$范围',函数($范围){}]);app.controller('twoCtrl',['$范围',函数($范围){}]);

然后我展示与 NG-视图内容:

 < D​​IV CLASS =NG-视图>< / DIV>

事情运作良好,但我需要从一个JSON文件加载数据来填充应用程序的所有内容。我要的是制造和AJAX调用的只有一次,然后通过我的所有不同的控制器传递数据。在我第一次尝试,我想创造它里面用 $ http.get()服务,包括在每一个控制器,但它不工作,因为它使不同的Ajax请求每次我和注射使用的服务。由于我是新采用了棱角分明我想知道什么是最好的方式或更多的角的方式来实现这一点没有搞乱它。

编辑:我添加服务,这仅仅是一个简单的 $ http.get 请求code:

  app.service('数据',['$ HTTP',函数($ HTTP){
    this.get =功能(){
        $ http.get('data.json')
        .success(功能(结果){
            返回结果;
        })
    }
});


解决方案

试试这个从获取链接获取JSON数据:

 (功能(应用程序){
    使用严格的;    app.factory('为myService',为MyService);    。为MyService $注射='$ Q,$ HTTP'];    功能为MyService($ Q $ HTTP){
        VAR的数据;        VAR的服务= {
            的getData:的getData
        };        退换货服务;        //////////////////////////////////////        函数的getData(刷新){
            如果(刷新||!数据){
                返回$ http.get('your_source'),然后(功能(数据){
                    this.data =数据;
                    返回的数据;
                })
            }
            其他{
                变种deferrer = $ q.defer();
                deferrer.resolve(数据);
                返回deferrer.promise;
            }
        }
    }}(angular.module('应用')));

现在你可以添加在你的控制器文件,并使用这种依赖关系:

  myService.getData()。然后(功能(数据){
    //此处使用的数据
},功能(错误){
    //这里处理错误
});

I'm working on a mobile app using AngularJS as a framework, currently I have a structure similar to this:

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'homeCtrl'
        })

        .when('/one', {
            templateUrl : 'pages/one.html',
            controller  : 'oneCtrl'
        })

        .when('/two', {
            templateUrl : 'pages/two.html',
            controller  : 'twoCtrl'
        });
}]);

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

}]);

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

}]);

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

}]);

And then I'm displaying the content with an ng-view:

<div class="ng-view></div>

Things are working well but I need to load data from a JSON file to populate all the content of the app. What I want is to make and an AJAX call only once and then pass the data through all my different controllers. In my first attempt, I thought to create a Service with an $http.get() inside of it and include that in every controller, but it does not work because it makes a different ajax request everytime I inject and use the service. Since I'm new using angular I'm wondering what is the best way or the more "angular way" to achieve this without messing it up.

Edit: I'm adding the code of the service, which is just a simple $http.get request:

app.service('Data', ['$http', function($http) {
    this.get = function() {
        $http.get('data.json')
        .success(function(result) {
            return result;
        })
    }
});

解决方案

Try this to get JSON Data from a GET Link:

(function (app) {
    'use strict';

    app.factory('myService', MyService);

    MyService.$inject = ['$q', '$http'];

    function MyService($q, $http) {
        var data;

        var service = {
            getData: getData
        };

        return service;

        //////////////////////////////////////

        function getData(refresh) {
            if (refresh || !data) {
                return $http.get('your_source').then(function(data){
                    this.data = data;
                    return data;
                })
            }
            else {
                var deferrer = $q.defer();
                deferrer.resolve(data);
                return deferrer.promise;
            }
        }
    }

}(angular.module('app')));

Now you can add this dependency in your controller file and use:

myService.getData().then(function(data){
    //use data here 
}, function(err){
    //Handle error here
});

这篇关于AngularJS应用程序:从JSON一旦加载数据,并在多个控制器使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆