json - 在 Hot Towel Angular 数据上下文中使用 return $q.when

标签 json http angularjs hottowel q

我已经使用 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;
  });
}

数据值设置为未定义

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

最佳答案

解决方案:

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


并且在 Controller 中,您可以使用返回的json对象,如下所示:

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

关于json - 在 Hot Towel Angular 数据上下文中使用 return $q.when,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914280/

相关文章:

php - Json:PHP 到 JavaScript 安全与否?

json - 在 Unity IL2CPP 脚本后端使用 JsonConvert.SerializeObject 的问题

ios - 尽管响应数据不为 NULL,NSURLConnection 从服务器获取 NULL 值 - iOS

html - 在 OCaml 网络爬虫中跟踪 HTTP 重定向

javascript - $viewContentLoaded 没有触发

javascript - 如何找到 json 文件的长度?

c++ - 在 C++ 中,我在使用队列和 libcurl 时遇到错误

JavaScript 和 SVG。有没有办法检测文本是否已呈现?

javascript - 路由时 Angular JS 路由参数约束

django - HttpResponse 与渲染