变量调用在订户函数外部返回值'undefined'

问题描述 投票:0回答:1

之前已经问过类似的问题,并且收到了很多答复,我可能对某人重复,但这只是急切需要的第三只眼。我正在按角度为订阅者函数内的变量分配一个值,但是当在订阅函数外调用时,该变量返回“未定义”。这是在做什么:

    this.invoiceService.buildDataForDiscountGraph(this.usrId, this.currentYear)
      .subscribe( response => {
        this.discountsGraphData += response;
        //this.discountGraphData is of type 'string'
    });
This.discountsGraphData

在订户内部调用,但在订户外部,在另一个函数中,甚至在我的模板中,它都是一个空字符串,返回所需的值。

这是buildDataForDiscountGraph()函数的外观:

buildDataForDiscountGraph(u,y){
    return this.getUserInvoices(u)
      .pipe(
        map(response  => {
          if(Object.keys(response).length > 0)
          {
            let jan = 0, feb = 0, mar = 0, apr = 0;
            let may = 0, june = 0, july = 0, aug = 0;
            let sep = 0, oct = 0, nov = 0, dec = 0;

            for(let x = 0; x < Object.keys(response).length; x++) {
              let dateSplit = response[x]['datecreated'].split('-');
              let year = dateSplit[0];
              let month = dateSplit[1];

              if(y == year){
                if(month == '01')jan += response[x]['discount'];
                if(month == '02')feb += response[x]['discount'];
                if(month == '03')mar += response[x]['discount'];
                if(month == '04')apr += response[x]['discount'];
                if(month == '05')may += response[x]['discount'];
                if(month == '06')june += response[x]['discount'];
                if(month == '07')july += response[x]['discount'];
                if(month == '08')aug += response[x]['discount'];
                if(month == '09')sep += response[x]['discount'];
                if(month == '10')oct += response[x]['discount'];
                if(month == '11')nov += response[x]['discount'];
                if(month == '12')dec += response[x]['discount'];
              }
            }

            return [
              jan, feb, mar, apr, may, june, july, aug,
              sep, oct, nov, dec
            ].join();
          }  
      })
    )
  }

我不得不将代码移到我的服务中,以试图找出导致它的原因。服务函数getUserInvoices()像这样调用端点;

/**
   * Get Invoices
   *
   * @param userId
   * @param Limit
   * @param Offset
   */
  getUserInvoices(usrId, limit?, offset?){
    return this.http.get(this.apiEndPoint + usrId + '/invoices?limit=' + limit + '&offset=' + offset)
      .pipe(
        map( data =>
          {
            return (data ? data : []);
          }
        )
      )
  }
javascript angular typescript angular-components angular9
1个回答
0
投票

您可以使用功能在订户外部设置this.discountGraphData

this.invoiceService.buildDataForDiscountGraph(this.usrId, this.currentYear)
  .subscribe( response => {
      this.setDate(response);
    //this.discountsGraphData += response;
    //this.discountGraphData is of type 'string'
});

setDate(data){
    this.discountsGraphData = data;
    console.log(this.discountsGraphData);  --> you will get value here.
}
© www.soinside.com 2019 - 2024. All rights reserved.