gpt4 book ai didi

javascript - 我如何将服务响应数据放入 md 对话框 angularjs?

转载 作者:行者123 更新时间:2023-11-30 11:58:51 25 4
gpt4 key购买 nike

我已经创建了这样的自定义服务

  app.service('userService', function($http,UrlService) {
return {
init: function(callback) {
$http.get(UrlService.baseUrl +'/api/users/list').then(function(user_response) {
callback(user_response);

});
}
}
})

在我的项目主 Controller 中,我像这样使用它来获取 Angular Material 设计模式。

  $scope.replyComplaint = function(user,complaint_id) {

complaint_id=user._id;
console.log(complaint_id)
$mdDialog.show({
controller: DialogCtrl,
templateUrl: 'submodules/user_management/replydialog.html',
resolve: { complaint_id : function() {return complaint_id;} },
locals: {
users: $scope.users
},
parent: angular.element(document.body),
clickOutsideToClose: true,
})
.then(function(response) {
$scope.response = response;
console.log(response);
}, function() {
//fail
});
};

如下在 Angular Material 文档中为对话创建了另一个 Controller

function DialogCtrl($scope, $rootScope, $mdDialog, users,complaintService, UrlService, $http) {
complaintService.init(function(complaint_response) {
$scope.complaints = complaint_response.data;
$scope.getUsers();
});

$scope.getUsers = function(complaint_id) {
console.log(complaint_id);
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.replyMail = function(complaint_id) {
console.log(complaint_id);
$http.post(UrlService.baseUrl + '/api/complaints/complaint/'+complaint_id , {
complaint: "replyText"
}, $scope)
.then(function(response) {
console.log(name);
$state.reload();
}, function(response) {
console.log(name);
});
}
}
}

现在,我需要在 DialogController 中获取 user_response 数据。如果我将 console.log('$scope.users') 放入此 userservice.init 函数中,我可以获得数据。但不在它之外。如何在userService.init函数之外获取响应数据

 userService.init(function(user_response) {
$scope.users = user_response.data;
}); //this is added in DialogController

主要目的是获取回复邮件功能的post请求中的user.comlaint_id。 user.complaint_id 是 user_response 的一部分任何人都请帮助我。谢谢

最佳答案

$http.get 调用返回一个 promise ,您可以直接使用它。

app.service('userService', function($http,UrlService) {
return {
init: function(callback) {
return $http.get(UrlService.baseUrl +'/api/users/list');
}
}
});

Controller :

function Dialog($scope,$rootScope, $mdDialog,userService,UrlService,$http) {
// console.log(userService.init());

init();

function init() {
userService.init().then(function(response) {
$scope.users = response.data;
});
}
}

这还具有更容易处理错误的优点:

function Dialog($scope,$rootScope, $mdDialog,userService,UrlService,$http) {
// console.log(userService.init());

init();

function init() {
userService.init().then(function(response) {
$scope.users = response.data;
}, function(error) {
// handle error
});
}
}

您应该阅读 angular/javascript promise 及其链接机制:angular promises

关于javascript - 我如何将服务响应数据放入 md 对话框 angularjs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185523/

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