AJAX加载JSON数据并将其存储在angularjs服务中

时间:2022-01-11 16:56:53

I am new at AngularJS. I am realy sorry if my question is stupid, but I can't find decision for two days. So, I have a service, which must load data via $http to itself during initialization and store it. I found some info about promises, but it will load data every time when I access it. But I would like that this data was loaded once and can be changed and saved. For better understanding this is how I would like

我是AngularJS的新人。如果我的问题很愚蠢,我真的很抱歉,但我找不到两天的决定。所以,我有一个服务,它必须在初始化期间通过$ http加载数据并存储它。我找到了一些关于promises的信息,但是每当我访问它时它都会加载数据。但我希望这些数据加载一次,可以更改和保存。为了更好地理解这是我想要的

app.run(function ($http, MeasurUnitsService) {
        $http.get('jsonData/tabs.json').success(function (data) {
            MeasurUnitsService.tabs = data;
        });

        $http.get('jsonData/measurmentUnits.json').success(function(data){
            MeasurUnitsService.measurmentUnits = data;                      
        });
    });


angular.module("emis-calc").service('MeasurUnitsService', function($http){  
     var tabs = {};
    var measurmentUnits = {};   
    var ConvertTo = function(){
        // some logic with accessing to measurmentUnits 
        // measurmentUnits is empty
        return result;
    }
    return {
        convertTo : ConvertTo,
        tabs : tabs,
        measurmentUnits : measurmentUnits
    }       
})

But as far as I understand, because $http.get() is Asynchronous and closures, MeasurUnitsService.tabs and MeasurUnitsService.measurmentUnits always is {}at controllers and other services. I feel that it is easy to implement, but can't find it at all. Maybe there is any lock() method? Also, if it isn't too difficult, could you explain more detailed and where is my main mistakes.

但据我了解,因为$ http.get()是异步和闭包,MeasurUnitsService.tabs和MeasurUnitsService.measurmentUnits总是{}在控制器和其他服务。我觉得它很容易实现,但根本找不到它。也许有任何lock()方法?此外,如果不是太难,你能解释得更详细,我的主要错误在哪里。

1 个解决方案

#1


2  

You should extract your http request in a service, and use that service in your controllers.

您应该在服务中提取http请求,并在控制器中使用该服务。

angular.module("emis-calc").service('MeasurUnitsService', function($http){  
   var tabs = null; 
  
   function getTabs(cb) {
     if(tabs) {
       cb(tabs) 
     } else {
       $http.get('jsonData/tabs.json').success(function (data) {
         tabs = data;
         cb(tabs);
       });
     }
   }
  
    return {
      getTabs
    }

This way your data only gets loaded once.

这样,您的数据只会加载一次。

#1


2  

You should extract your http request in a service, and use that service in your controllers.

您应该在服务中提取http请求,并在控制器中使用该服务。

angular.module("emis-calc").service('MeasurUnitsService', function($http){  
   var tabs = null; 
  
   function getTabs(cb) {
     if(tabs) {
       cb(tabs) 
     } else {
       $http.get('jsonData/tabs.json').success(function (data) {
         tabs = data;
         cb(tabs);
       });
     }
   }
  
    return {
      getTabs
    }

This way your data only gets loaded once.

这样,您的数据只会加载一次。