[英]AngularJS factory retuning undefined object from $http
我正在工厂中使用$http
指令从AngularJS应用程序进行API调用(我已经尝试过$http
和$resource
并且我并不在乎只要使用它返回数据就可以使用它),并且我当我不使用.then()
来解开promise或undefined
时,将得到$$state
对象。
这是工厂代码:
app.service('dataService', ['$http', function($http) {
return {
quizQuestions: function() {
return $http.get("http://localhost:59143/api/Questions")
.then(function(response) {
console.log(response);
console.log(response.data);
console.log(response.data[0]);
return response;
})
}
}
}])
当我从控制器调用它时,我这样做:
app.controller('QuizController', ['$scope', '$http', 'dataService', function($scope, $http, dataService) {
dataService.quizQuestions().then(function(data) {
$scope.quizQuestions=data;
console.log($scope.quizQuestions);
})
}])
在这一点上,我什至没有尝试将数据绑定到视图,而只是观察控制台输出。 我在控制台中得到的配置是这样的:
{data: array(1), status: 200, heders: f, config: {...}, statusText: "OK"}
[{...}]
{Text: "...", *rest of object omitted for brevity but it is here*}
undefined
谁能告诉我我在做什么错?
顺便说一句,当我一起消除工厂并将代码保存在控制器中时:
app.controller('QuizController',['$scope', '$http', function($scope, $http) {
$http.get("http://localhost:59143/api/Questions").then(function(response) {
console.log(response);
console.log(response.data);
console.log(response.data[0]);
$scope.quizQuestions=response.data;
console.log($scope.quizQuestions);
console.log($scope.quizQuestions[0]);
})
}])
我得到以下控制台输出:
{data: array (etc)}
[{...}]
{text: (rest of obj)}
[{...}]
{text: (rest of obj)}
好像是工厂里的东西吗?
我在其他文章中已经找到了一些方向和角度文档,但无济于事。
在您的服务中,您已经解开了$ http返回的promise。
所以要么
...
quizQuestions: function() {
return $http.get("http://localhost:59143/api/Questions");
}
...
要么
在您的服务中使用.then(),但返回这样的承诺,
但不要忘记添加$ q作为依赖项 ,
quizQuestions: function() {
let defer = $q.defer();
$http.get("http://localhost:59143/api/Questions").then(function(response) {
// ...
defer.resolve(response); // or whatever you want to return
}, function (error) {
defer.reject(error);
})
return defer.promise;
}
因此,基本上在您的服务中,您解开了Promise,然后返回了一个静态值。
现在,在控制器中,您正在调用服务,并尝试将then()应用于不返回promise的函数。
data
作为response
对象的属性附加:
app.controller('QuizController', ['$scope', '$http', 'dataService', function($scope, $http, dataService) {
dataService.quizQuestions().then(function( ̶d̶a̶t̶a̶ response) {
̶$̶s̶c̶o̶p̶e̶.̶q̶u̶i̶z̶Q̶u̶e̶s̶t̶i̶o̶n̶s̶=̶d̶a̶t̶a̶;̶
$scope.quizQuestions=response.data;
console.log($scope.quizQuestions);
})
}])
从文档中:
$http
返回将通过响应对象解决(请求成功)或被拒绝(请求失败)的承诺 。
响应对象具有以下属性:
- data –
{string|Object}
–使用转换函数转换的响应主体。- status –
{number}
–响应的HTTP状态代码。- 标头 –
{function([headerName])}
–标头获取函数。- config –
{Object}
–用于生成请求的配置对象。- statusText –
{string}
–响应的HTTP状态文本。- xhrStatus –
{string}
– XMLHttpRequest的状态(complete
,error
,timeout
或abort
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.