【发布时间】:2023-03-03 04:00:01
【问题描述】:
我有一个关于 AngularJS 中的承诺系统和服务创建的问题。我有一个名为 Customer 的服务:
angular.module("app").factory("Customer", ["CustomerDBServices", "OfficesList", "$q",
function(CustomerDBServices, OfficesList, $q){
return function(customerID){
var self = this;
//attributes
this.name = null;
this.ID = null;
this.code = null;
this.isVisible = 1;
this.showOffices = true;
this.offices = new OfficesList();
//constructor
if(typeof customerID !== "undefined"){
var metacustomer = CustomerDBServices.find({ID:customerID}, function(){
self.name = metacustomer.results.customer_name;
self.ID = metacustomer.results.customer_ID;
self.code = metacustomer.results.customer_internal_code;
self.isVisible = metacustomer.results.customer_is_visible;
self.getOffices();
});
}
//add office to customer
this.addNewOffice = function(){
self.offices.addNewOffice();
};
//remove office from customer
this.removeOffice = function(officeIndex){
self.offices.removeOffice(officeIndex);
};
//show offices
this.toggleOfficeVisibility = function(officeIndex){
self.offices.toggleOfficeVisibility(officeIndex);
};
}]);
在该服务的“构造器”部分,有一个对服务的 AJAX 调用,该服务从数据库中加载客户的属性。这是一个异步任务。在这种情况下如何创建承诺?我这样使用客户服务:
var customer = new Customer(ID);
我想做类似的事情
var customer = new Customer(ID).then(
function(){...}, //success
function(){...} //error
);
为此,我需要一个承诺。我必须在客户服务中编写方法create() 吗?
angular.module("app").factory("Customer", ["CustomerDBServices", "OfficesList", "$q",
function(CustomerDBServices, OfficesList, $q){
return function(customerID){
var self = this;
//attributes
this.name = null;
this.ID = null;
this.code = null;
this.isVisible = 1;
this.showOffices = true;
this.offices = new OfficesList();
//costructor
this.create = function(){
if(typeof customerID !== "undefined"){
var rest = $q.defer();
var metacustomer = CustomerDBServices.find({ID:customerID}, function(){
self.name = metacustomer.results.customer_name;
self.ID = metacustomer.results.customer_ID;
self.code = metacustomer.results.customer_internal_code;
self.isVisible = metacustomer.results.customer_is_visible;
self.getOffices();
rest.resolve("ok!");
});
return rest.promise;
}
}
...
...
...
}]);
然后像这样使用那些东西?
var customer = new Customer();
customer.create(ID).then(
function(){...},
function(){...},
)
难道没有办法调用“新客户”并获得承诺吗?提前谢谢!
【问题讨论】:
-
我强烈建议不要这样做。不要将复杂的异步逻辑放在构造函数中,这会很混乱。
-
感谢您的建议。那么您是否建议在女巫中创建一个“retrieveCustomer”方法来放置异步创建的东西?
-
是的,我还将添加一个关于您如何可以 完成此任务的答案以及您可能不应该这样做的说明。如果我是你,我也会承诺
CustomerDBServices服务。
标签: javascript angularjs asynchronous service promise