Angular-订阅返回

我正在尝试使用订阅将值返回到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返回。但是我无法理解有关如何解决此问题的方法。

评论
lillo
lillo

您正在与Observable异步工作,因此您需要使用回调,例如Promise。您应该在方法中返回一个Observable(或Promise),并让调用者订阅它:

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;

    return this.userService.getVoucher(vouchernotopass,vouchertype).pipe(
        map(res => {
          voucherdate = res['voucherdate'];
          enteries = res['enteries'];
          return { "vouchertype":vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "enteries":enteries};   
        })
    );       
}

像这样使用这种方法:

getVoucherDetails(id).subscribe(v => {
  console.log(v.vouchertype);
  console.log(v.vouchernumber);
  console.log(v.voucherdate);
});

在您的情况下:

forkJoin( // forkJoin waits for Observables to complete and then combine last values they emitted.
   this.voucherIDs.map(id => this.getVoucherDetails(id) // array of observable
).subscribe(responses => {
   console.log(responses);
});
点赞
评论