angular.js - angular下,只请求一次远程json数据,便可在多个控制器下使用
巴扎黑
巴扎黑 2017-05-15 17:06:02
0
3
541

1.目的:期望该远程数据(json.json)需要重复利用,希望只请求一次json.json数据,可以在多个控制器中反复使用
2.问题:路由每跳转一次,就会重新请求一次'json.json'

3.代码如下
<script>

angular.module("myApp",[])
        .factory("$remoteData",['$http',function($http){
            return $http.get("../json/json.json").then(function(response){
                //获取 远程数据 服务
                //目的:期望该远程数据(json.json)需要重复利用,希望只请求一次json.json数据,可以在多个控制器中反复使用
                //问题:路由每跳转一次,就会重新请求一次'json.json'
                console.log(response.data);
                var myData = "";
                return myData = response.data;
            })
        }])
        .factory("$localData",function(){
            return {"name":"wenwu","age":"26"};
        })
        .controller("FirstController",function($scope,$remoteData,$localData){
                //远程请求的数据 --获取失败(如果这里能够获取json.json的数据,应该就成功了)
                $scope.remoteData = $remoteData;
                console.log('$scope.remoteData',$scope.remoteData);//返回 $scope.remoteData d {$$state: Object}
                console.log('$scope.remoteData.$$state.value',$scope.remoteData.$$state.value);//返回undefined

                //本地制作的数据 -- 获取成功
                $scope.localData = $localData;
                console.log($scope.localData);//返回 Object {name: "wenwu", age: "26"}
        })

</script>

巴扎黑
巴扎黑

reply all(3)
过去多啦不再A梦

You can try this:

factory("$remoteData",['$http', '$q', function($http, $q){
    var self = this;
    
    function getData() {
        if (self.myData) {
            return $q(function(resolve, reject) {
                resolve(self.myData);
            });
        } else {
            return $http.get("../json/json.json").then(function(response){
                self.myData = response.data;
                return self.myData;
            });
        }
    }
    return {getData: getData}
}]);

Use it like this in the controller:

.controller("FirstController",function($scope,$remoteData,$localData){
    $remoteData.getData().then(function(myData) {
        //use myData
    });
});
滿天的星座

Use service singleton, hang the object reference on the service object, and fetch this object directly later

刘奇

Angular has the root scope $rootScope. You can persist the data common to each controller to the root scope and obtain it only once through appropriate methods.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!