scope.members控制器中的警告始终为空,但在服务中它从服务器获取数据。不知何故,来自服务器的数据在服务中的get函数和控制器的回调之间丢失。
控制器:
AndreaApp.controller('MemberDetailController', ['$scope', '$rootScope','$http','$location','$routeParams','MemberService','MemberGroupsService','ArrivalsService','WarningsService','NotificationsService',function (scope,rootScope, http,location,routeParams,MemberService,MemberGroupsService,ArrivalsService,WarningsService,NotificationsService) {
scope.member = MemberService.get(routeParams.id);
scope.membersGroup = MemberService.membersGroup(routeParams.id);
scope.membersWarnings = WarningsService.get(routeParams.id);
scope.editMember = function(id){
location.path('/editMember/'+id);
}
scope.membersDocument = function(id){
location.path('/membersDocument/'+id);
}
scope.templates =
[ { name: 'packages.html', url: 'views/members/packages.html'},
{ name: 'notifications.html', url: 'views/members/notifications.html'},
{ name: 'warnings.html', url: 'views/members/warnings.html'},
{ name: 'arrivals.html', url: 'views/members/arrivals.html'} ];
scope.template = scope.templates[0];
scope.loadTemplate = function(templateId){
if(templateId == 3){
scope.arrivals = ArrivalsService.get(routeParams.id).arrivalsId;
console.log(scope.arrivals);
}
scope.template = scope.templates[templateId];
}}]);
WarningsService:
AndreaApp.service('WarningsService', function ($http,$q) {
var warnings = [];
this.save = function (warnings, memberId) {
$http.post('/api/warnings/new/member/'+memberId,
{
name: warnings.name,
description: warnings.description,
readed: false,
clanId: memberId
}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
alert("Error occurred while adding a warning. HTTP Respone: " + status);
});
}
this.get = function (id) {
var deferred = $q.defer();
$http.get('/api/warnings/member/'+id).
success(function(data, status, headers, config) {
warnings.length = 0;
console.log(data);
for(var i = 0; i < data.length; i++){
warnings.push(data[i]);
}
deferred.resolve(data);
//data exists here, it is not empty
}).
error(function(data, status, headers, config) {
alert("HTTP status:" + status)
});
return deferred;
}});
答案 0 :(得分:1)
您可以返回$ http,如下所示:
this.get = function (id) {
return $http.get('/api/warnings/member/'+id);
}
然后你可以在Controller上使用它。
WarningsService.get(routeParams.id).then(function(result){
$scope.membersWarnings = result.data; // or just result
});
你不能像你一样分配,因为你以这种方式回复了一个承诺。结果还没有准备就绪
答案 1 :(得分:0)
scope.member = MemberService.get(routeParams.id);
应该是
MemberService.get(routeParams.id).then(function(data) {
scope.member = data;
});
这是因为你的get方法正在返回一个promise,所以一旦解析,你就可以获得数据。
此外,您的get方法需要更改为
return deferred.promise;