【问题标题】:Using return $q.when in Hot Towel Angular datacontext在 Hot Towel Angular 数据上下文中使用 return $q.when
【发布时间】:2014-01-03 23:01:33
【问题描述】:

我已经使用 Hot Towel Angular 模板创建了一个 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;
  });
}

数据的值设置为undefined

我遗漏了一些东西,请帮助找出错误。

【问题讨论】:

  • 您的$q.when(f) 只是将空数组[](即执行返回时f 的当前值)包装到一个promise 中。然后立即使用此值解决此承诺,即使用 data=[] 调用您的 then-callback。
  • 好的,我明白了,但是有什么解决方案可以使这项工作?

标签: json http angularjs hottowel q


【解决方案1】:

解决方案:

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

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;
  });
}

【讨论】:

  • 这真的是正确的答案吗?对我来说,返回 $http 承诺完全违背了使用数据上下文的目的,因为它向消费者公开了数据访问实现细节。消费者将依赖于数据访问实现,因此您将无法在不更改消费者的情况下使用缓存策略或伪造。在我看来,最初的想法很好,只是实施得不好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
相关资源
最近更新 更多