【发布时间】:2019-02-07 20:31:08
【问题描述】:
我正在使用 angularJs v1.7
我需要从工厂加载我的对象,这工作得很好:
$scope.equipe = equipesFactoryLocalStorage.getEquipeMomentanee();
现在,我需要像这样添加一个 .then(),因为我需要在对象加载后做一些事情:
equipesFactoryLocalStorage.getEquipeMomentanee().then(function(response){
$scope.equipe = response;
})
AngularJs 在控制台中提供了这个错误:
TypeError: "equipesFactoryLocalStorage.getEquipeMomentanee(...).then is not a function"
几个小时以来我一直在为此苦苦挣扎,请帮助我。
这是我的工厂:
monApp.factory('equipesFactoryLocalStorage',function(){
var factory = {};
/* Charger une equipe momentanee */
factory.getEquipeMomentanee = function(equipe){
if(JSON.parse(localStorage.getItem("equipe"))!=null){
var equipe = JSON.parse(localStorage.getItem("equipe"));
}
else{
var equipe = {};
equipe.attaquants = [];
equipe.ailiers_gauche = [];
equipe.attaquants_soutien = [];
equipe.ailiers_droits = [];
equipe.milieu_gauche = [];
equipe.milieu_soutien = [];
equipe.milieu_droit = [];
equipe.defense_gauche = [];
equipe.defense_soutien = [];
equipe.defense_droit = [];
equipe.liberos = [];
equipe.goal = [];
equipe.img = "img/new.png";
equipe.date_creation = new Date();
}
return equipe ;
}
return factory
})
请帮助我,我不明白为什么 .then() 不工作,而没有 .then() 工作 我试过使用 angularjs 1.5 ,并且有同样的错误。
我看过几篇关于这个的帖子,没有人在工作,我试过这个:
equipesFactoryLocalStorage.getEquipeMomentanee().$promise.then(function(response){
$scope.equipe = response;
})
它也不起作用。不是双发,真的不行。
编辑:谢谢 Frank Modica,现在已解决:
我已经像这样改变了我的工厂(请注意 $q):
monApp.factory('equipesFactoryLocalStorage',function($q){
var factory = {};
/* Charger une equipe momentanee */
factory.getEquipeMomentanee = function(equipe){
if(JSON.parse(localStorage.getItem("equipe"))!=null){
var equipe = JSON.parse(localStorage.getItem("equipe"));
}
else{
var equipe = {};
equipe.attaquants = [];
equipe.ailiers_gauche = [];
equipe.attaquants_soutien = [];
equipe.ailiers_droits = [];
equipe.milieu_gauche = [];
equipe.milieu_soutien = [];
equipe.milieu_droit = [];
equipe.defense_gauche = [];
equipe.defense_soutien = [];
equipe.defense_droit = [];
equipe.liberos = [];
equipe.goal = [];
equipe.img = "img/new.png";
equipe.date_creation = new Date();
}
return $q.resolve(equipe);
}
return factory
})
现在,它运行良好,并且 .then() 正确返回了我的对象!
【问题讨论】: