如何直接从$http返回 JSON 对象

How to directly return JSON object from $http?

本文关键字:返回 JSON 对象 http 何直接      更新时间:2023-09-26

我想创建一个始终返回从 Web 服务检索到的json对象的factory

angular.module('test').factory('myService', myService);
myService.$inject = ['$http'];
function myService($http) {
    var urlBase;
    return {
        getContent: function(id) {
            return $http.get(urlBase).then(function(response) {
                return response.data;
            });
        }
    };
}

当我调用MyService.getContent();时,我得到的不是JSON对象,而是一个具有$$state__proto__的对象。

为什么?如何提前出厂直接只退货?

注意:我知道我可以写

MyService.getContent().then(function(response) { console.log(response); });

但这样,当我进入工厂时,我总是必须重复then... function语句。

不能返回异步函数的结果。您的return response.data;语句只是退出承诺.then()回调。你应该像这样修改你的函数:

getContent: function(id) {
  return $http.get(urlBase);
}

然后这样称呼它:

MyService.getContent().then(function (response) {
  // do something with the response
});

这是因为您返回的是一个已经解析的承诺,而不是承诺实例。刚回来

$http.get(urlBase)

从你的getContent函数应该做这个技巧:)