如何直接从$http返回 JSON 对象
How to directly return JSON object from $http?
我想创建一个始终返回从 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函数应该做这个技巧:)
相关文章:
- Jquery:对返回JSON数据的php脚本的Ajax调用
- 返回JSON中的下标
- jQuery Map 从多个源返回 JSON 对象
- 如何在 Node.js 中返回 JSON 后停止代码流
- AngularJS:表单提交没有返回JSON中的值
- 使用ajax发送数据,返回json
- 从我的解析函数返回json
- 如何从脚本页面返回json数据
- 有些人有任何关于如何使用Modified Java Script Value处理返回Json(url)的示例
- 如何在html页面中从ajax返回json数据
- Ajax调用在本地返回json,但在服务器上运行时返回xml
- ajax调用返回JSON ParseError即使认为JSON看起来是正确的
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何通过C#返回JSON并用JavaScript进行解析
- 使用 AJAX 返回 json 数组
- 从 AJAX 命令返回 JSON 格式的响应
- 如何通过node中的请求返回JSON.js(从javascript)
- Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
- 如何在支柱 2 中返回 JSON 数组
- Rhino:从 Java 中返回 JSON