gpt4 book ai didi

javascript - AngularJS 服务获取数据,但不将其返回给 Controller ?

转载 作者:行者123 更新时间:2023-12-03 10:15:20 26 4
gpt4 key购买 nike

Controller 中的scope.membersWarnings始终为空,但在服务中它从服务器获取数据。不知何故,我来自服务器的数据在服务和 Controller 中的 get 函数的回调之间丢失了。

Controller :

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];
}}]);

警告服务:

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;
}});

最佳答案

您可以只返回 $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
});

你不能像你正在做的那样分配,因为你以这种方式返回一个 promise 。此时结果尚未准备就绪

关于javascript - AngularJS 服务获取数据,但不将其返回给 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29900882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com