【发布时间】:2018-09-02 10:57:47
【问题描述】:
我在工厂中使用$http 指令从我的AngularJS 应用程序进行API 调用(我已经尝试了$http 和$resource,我并不关心我使用哪个,只要它返回数据),当我不使用.then() 来解开承诺或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)}
所以它似乎是工厂里的东西?
我查看了这些其他文章以获得一些方向和角度文档,但无济于事。
【问题讨论】:
-
不是重复的,事后尝试了 .then() ,这就是我遇到问题的时候。如果我只是执行以下操作,我可以获得完整的 http 对象:$scope.quizQuestions=dataService.quizQuestions()。只有当我执行 .then() 时,我才会得到未定义。
-
现在您的代码似乎没问题。如果可能,请尝试创建 Minimal, Complete, and Verifiable example 以重现错误。
标签: javascript angularjs api