我正在尝试使用订阅将值返回到this.voucherDetails,但它似乎不起作用。
以下是对具有订阅功能的功能getVoucherDetails的请求。
voucherIDs: string[];
voucherDetails: Promise<any>[];
this.voucherIDs = ['JV-2005-50','JV-2005-40','JV-2005-30'];
this.voucherDetails = this.voucherIDs
.map(id => this.getVoucherDetails(id));
Promise.all(this.voucherDetails)
.then(() => this.printService.onDataReady());
以下是订阅userService的函数,该函数从数据库获取数据。
getVoucherDetails(voucherid) {
var splitvoucher = voucherid.split('-');
var vouchertype = splitvoucher[0];
var vouchermy = splitvoucher[1];
var voucherno = splitvoucher[2];
var vouchernotopass = vouchermy+"-"+voucherno;
var voucherdate;
var enteries;
this.userService.getVoucher(vouchernotopass,vouchertype).subscribe(
res => {
voucherdate = res['voucherdate'];
enteries = res['enteries'];
return { "vouchertype":vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "enteries":enteries};
}
);
}
但是它返回未定义的。经过几篇文章后,我了解到您无法从.subscribe返回。但是我无法理解有关如何解决此问题的方法。
您正在与Observable异步工作,因此您需要使用回调,例如Promise。您应该在方法中返回一个Observable(或Promise),并让调用者订阅它:
像这样使用这种方法:
在您的情况下: