AngularJS:为什么我的控制器得到'undefined'我的服务电话
AngularJS: Why does my controller get 'undefined' from my service call?
问题:我的服务正在检索正确的信息,那么为什么我的控制器不能从我的服务获取数据?
Service:这是我的控制器(以及其他东西)调用的代码。
// search.service.js
(function () {
'use strict';
angular.
module('trips').
factory('SearchService', SearchService);
SearchService.$inject = ['BoatList'];
function SearchService(BoatList) {
var service = {
getBoatList: getBoatList
};
return service;
//////////////////////
function getBoatList() {
BoatList.query()
.$promise
.then(function (data) {
console.log(data);
return data;
})
.catch(function (error) {
return error;
})
}
}
})();
Console Information:
这就是为什么我这么困惑。服务将Array[7]
作为API调用中.then()
的一部分记录到控制台。数组包含我想要的数据。由于某些原因,我似乎无法在控制器中访问它。当我用调试器运行它时,我得到'undefined'
。
Controller:当我调用与服务的getBoatList
相同的代码时,一切工作正常。当我试图访问从activate()
返回的数据时,我没有得到任何错误,只是'undefined'
。
//search.controller.js
(function () {
'use strict';
angular.
module('trips').
controller('SearchController', SearchController);
SearchController.$inject = ['$stateParams', 'SearchService'];
function SearchController($stateParams, SearchService) {
var vm = this;
vm.boatList = null;
activate();
////////////////////
function activate() {
vm.boatList = SearchService.getBoatList();
}
}
})();
概述:我的服务获取正确的数据并将其记录到控制台。我的控制器没有通过调用服务获得相同的信息。我该如何解决这个问题,是什么误解导致了我的这个问题?
你必须在你的工厂更改方法,因为方法getBoatList
应该返回一个承诺。
将您的工厂方法更改为:
function getBoatList() {
return BoatList.query().$promise;
}
在控制器中,必须将activate
方法更改为:
function activate() {
SearchService.getBoatList()
.then(function (data) {
vm.boatList = data;
})
.catch(function (error) {
// do smth on error
});
}
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- /undefined在我的404错误日志中多次出现
- 为什么ajax回调在我的本地变量中设置undefined
- 为什么我的回拨说“;undefined不是函数
- 为什么我的React组件's ref在测试中等于undefined ?
- 为什么我的函数返回undefined
- AngularJS:为什么我的控制器得到'undefined'我的服务电话
- 为什么我的Angular控制器是undefined ?
- 为什么调用我的函数返回undefined
- 获取'undefined'在控制器中使用我的工厂时出现错误
- Get "undefined不是函数"当我试图使用我的收藏
- 为什么JS小提琴给我的错误'未捕获TypeError: undefined不是一个函数'
- 为什么我的数组过滤器返回'undefined不是一个函数'
- 为什么这个undefined一直出现在我的演示中
- 检查javascript中的undefined——我是否应该使用typeof
- 为什么我的Angular服务说";undefined不是函数";当我通过函数时
- 为什么我的函数返回undefined
- 在我的谷歌搜索API调用中,它返回一个有效的JSON,但每当我解析它以获得特定值时,我都会得到Undefined
- 为什么我得到undefined而不是JavaScript中嵌套的对象属性值
- 为什么我的find方法返回undefined ?