【发布时间】:2015-07-11 05:05:23
【问题描述】:
好的,现在我正在搞乱 ionic 框架并同时学习 angularJS。我刚刚遇到 $q 和异步调用,但我似乎无法正确处理。我希望能够解析我已经使用 GetJsonSpecials 设置的 JSON 文件,然后将其传递给 GetData,然后将其传递给我的控制器 SpecialsCtrl,以便我可以将其附加到 $scope。我知道我没有正确理解这些承诺,因为 SpecialService 中的所有内容都未定义。我可以从其他两个服务中很好地获取数据,但是当我尝试将其传递给SpecialService 时,一切似乎都崩溃了,而这又在我的控制器中以未定义的形式结束。也许我没有以正确的方式解决这个问题?有没有做这种事情的最佳实践?
angular.module('starter.controllers', [])
.controller('SpecialsCtrl', function ($scope, SpecialService) {
$scope.specials = SpecialService.all();
console.log("Specials Controller: Got Data", $scope.specials);
})
//Create methods to access the specials inside the controller in which we inject this in
.factory('SpecialService', function (GetData) {
var specials = GetData.getSpecials();
console.log("DATAAAA: ", specials);
return {
// Return all specials
all: function () {
console.log("Inside return with specials: ", specials);
return specials;
},
getSpecialWithId : function (specialId) {
// Simple index lookup
return specials[i];
}
}
}
})
.factory('GetData', function(GetJsonSpecials) {
return {
getSpecials : function() {
GetJsonSpecials.retrieveData().then(function (data) {
console.log("Got the JSON data", data);
return data;
}, function (status) {
alert("Error getting specicals", status);
console.log("Error getting specicals", status);
});
}
}
})
//Asynchronously get the specials from the json file
.factory('GetJsonSpecials', function ($q, $http) {
return {
retrieveData : function() {
var deferred = $q.defer();
$http.get('js/specials.json').success(function (data, status) {
deferred.resolve(data);
}).error(function (status) {
deferred.reject(status);
console.log("Error in handling json!");
});
return deferred.promise;
}
}
})
之所以如此复杂,是因为最终我希望能够将数据共享给另一个控制器,该控制器将在新视图中显示特定特价商品的属性。
.controller('DetailCtrl', function ($scope, $stateParams, JsonSpecials, $firebaseAuth) {
$scope.id = parseInt($stateParams.specialId);
$scope.special = JsonSpecials.getSpecialWithId($scope.id);
})
【问题讨论】:
-
我不确定我是否理解您的 SpecialService 的意义。为什么不直接将 GetData 服务注入控制器并直接调用 getSpecials 方法?
-
因为我有两个控制器需要获取相同的数据,所以如果我这样做,那么我需要为另一个控制器重复代码。
标签: json angularjs controller ionic-framework factory