Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 在热数据上下文中使用return$q_Json_Http_Angularjs_Hottowel_Q - Fatal编程技术网

Json 在热数据上下文中使用return$q

Json 在热数据上下文中使用return$q,json,http,angularjs,hottowel,q,Json,Http,Angularjs,Hottowel,Q,我已经使用热模板创建了一个web应用程序,我想在“datacontext”中添加一个服务函数 代码是: (function () { 'use strict'; var serviceId = 'datacontext'; angular.module('app').factory(serviceId, ['common', '$http', datacontext]); function datacontext(common, $http) {

我已经使用热模板创建了一个web应用程序,我想在“datacontext”中添加一个服务函数

代码是:

(function () {
    'use strict';

    var serviceId = 'datacontext';
    angular.module('app').factory(serviceId, ['common', '$http', datacontext]);

    function datacontext(common, $http) {
        var $q = common.$q;

        var service = {
            getFunctions: getFunctions
        };

        return service;

        function getFunctions() {
            var f = [];
            $http({
                method: 'GET',
                url: 'https://api.github.com/users/google/repos',
                contentType: 'application/json; charset=utf-8'
            })
            .success(function (data, status, headers, config) {
                f = data;
                console.log('f=*' + f + '*');
            })
            .error(function (data, status, headers, config) {
                alert('error!');
            });

            return $q.when(f);
        }
    }
})();

我看到控制台显示了一些对象:

f=*[object Object],[object Object],[object O...
但在我的functionController.js文件中使用此选项时:

function getFunctions() {
  return datacontext.getFunctions().then(function (data) {
    console.log('data=*' + data + '*');
    return vm.functions = data;
  });
}
数据的值设置为未定义

我遗漏了一些内容,请帮助识别错误。

解决方案:

datacontext中的getFunctions函数应返回$http promise对象,如下所示:

function getFunctions() {
  return $http.get('https://api.github.com/users/google/repos')
    .error(function (data, status, headers, config) {
      alert('error ! : ' + status);
  });
}

控制器中,您可以使用返回的json对象,如下所示:

function getRepos() {
  return datacontext.getRepos().then(function (httpResult) {
    vm.repos = httpResult.data;
  });
}

您的
$q.when(f)
只需将执行返回时
f
的当前值的空数组
[]
包装成一个承诺。然后立即用这个值解决这个承诺,即,调用您的then回调函数时使用data=[]。好的,我明白了,但是什么样的解决方案可以让它工作呢?这真的是正确的答案吗?在我看来,返回$http承诺完全违背了使用数据上下文的目的,因为它向消费者公开了数据访问实现细节。使用者将依赖于数据访问实现,因此在不更改使用者的情况下,您将无法使用缓存策略或伪策略。在我看来,最初的想法是好的,只是执行得不好。