(Angularjs) 如何 $http.get 数据并将其存储在服务中 [英] (Angularjs) How to $http.get data and store it in service

查看:32
本文介绍了(Angularjs) 如何 $http.get 数据并将其存储在服务中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您将看到的,我是 AngularJS、JS 和 Web 开发方面的新手 =) 真的很抱歉,但我会尝试这样做.

As you will see i'm new in AngularJS, JS and in web development at all =) really sorry for that but i try to.

我尝试使用 AngularJS 控制器构建一个庞大的网络表单(大约 200 个不同的字段).我需要从控制器访问根数据源.AngularJS 团队要求不要仅仅为存储数据而创建服务,但我想为加载和保存数据提供服务(在开始到服务器上的 .json 文件中).

I try to build a massive webform (about 200 different fields) with AngularJS controllers. I need access from controller to root data source. AngularJS team ask do not make Services just for storing data, but i want to make service for load and save data (at start into .json files on a server).

服务:

AppName.factory('MasterData', ['$rootScope', '$http', '$q', '$log', 
    function($rootScope, $http, $q, $log) {

    var responseData;
    $http.get('/getdata.php').then(function (response) {
        responseData = response.data;
        console.log(response.data);
    });

    return responseData;

}]);

控制器:

AppName.controller('justController', ['$scope', 'MasterData', '$log',
    function ($scope, MasterData, $log) {
        $scope.data = MasterData.justControllerSectionData;
        console.log(MasterData);
    }
]);

控制器返回未定义.但是来自服务的 console.log 返回对象.我觉得这个问题太简单了,但我找不到如何解决它:(此外,我不能使用 .getData() 之类的函数从控制器到服务,因为它每次加载任何控制器时都会询问服务器的数据.我在 AngularJS 应用中有 12-14 个控制器的路由(完整的网络表单按部分划分),我认为从后端获取数据一次很好.

Controller return undefined. But console.log from service returns the object. I feel that the problem is too easy, but i can't find how to solve it :( Also i can't use function like .getData() from controller to service because it ask the data from server each time any controller loads. I have the routes in AngularJS app with 12-14 controllers (full webform divided by sections) and i think it is good to get the data from backend once.

附言我认为承诺有问题,但是当我尝试使用这样的代码时:

P.S. I think there is problem with promises, but when i try to use code like this:

var defer = $q.defer();
$http.get('/getdata.php').success(function(data){
    defer.resolve(data);
});
return defer;

我有决心、拒绝等对象.真的不明白我能用它做什么:(

I've got object with resolve, reject and so on. And really can't understand what can i do with it :(

帮我获取控制器中的数据:)

Help me to get the data in controller :)

推荐答案

您的代码不起作用,因为您在服务中提供给 success() 的回调是异步调用的;在您的服务返回后,即:

Your code doesn't work, because the callback you supplied to success() in your service is called asynchronously; after your service has returned, that is:

顺序是这样的:

  1. 运行 MasterData 中的 function.启动 $http.get 请求并附加承诺回调.responseData 在这个回调中被引用(又名关闭").
  2. 该函数从服务返回到您的控制器.responseData 尚未设置,这不会阻止父作用域函数返回.
  3. $http.get 成功并且 responseData 在服务中设置,但控制器无法访问.
  1. The function in MasterData is run. The $http.get request is launched and attached the promise callback. responseData is referenced in this callback (aka. "closed over").
  2. The function returns from the service to your controller. responseData has not been set yet, which doesn't stop the parent scope function from returning.
  3. $http.get succeeds and responseData is set in the service however unreachable for the controller.

如果您不清楚 success() 中嵌套函数的范围,我建议您阅读 JavaScript 中的闭包(或者更好,一般来说),例如 此处.

If the scoping of the nested function in success() is not clear to you, I'd recommend reading about closures in JavaScript (or even better, in general), for example here.

您可以通过这样的服务实现您的目标:

You can achieve your goal with a service like this:

function($q, $http, /* ... */) {    
    return {
        getData: function() {
            var defer = $q.defer();
            $http.get('/getdata.php', { cache: 'true'})
            .then(function(response) {
                defer.resolve(response);
            });

            return defer.promise;
    };
}

$http 服务很乐意缓存您的响应数据,因此您不必这样做.请注意,您需要从 deferred 对象中检索承诺才能使其工作.

The $http service will happily cache your response data, so you don't have to. Note that you need to retrieve the promise from your deferred object to make this work.

控制器是这样的:

/* omitted */ function($scope, YourService) {
    YourService.getData().then(function(response) {
        $scope.data = response.data;
    });
}

由于成功是折旧的,所以我将成功修改为那时.

Since success is depreciated, I modified success to then.

这篇关于(Angularjs) 如何 $http.get 数据并将其存储在服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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