如何在angular / Typescript中传递回调

时间:2018-07-12 20:25:10

标签: javascript html angular typescript angular6

我需要一个可以先运行的方法,由于ngOnInit,它在组件中可能更容易,但是在这里我使用的是服务,由于某种原因,回调会破坏代码。

runData方法是入口函数,它运行getSalesCounter(n)方法,该方法应该返回一个对象,但我一直未定义。我的半决赛猜测是angular在另一个服务中请求它之前返回空属性。我该怎么办,任何帮助将不胜感激,谢谢您

    import { Injectable } from '@angular/core';
import { DateService } from './date.service';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class ReportsService {
  server: any;
  processedData: object;

  constructor(
    public authService: AuthService,
    private dateService: DateService
  ) { }

  getSalesCounter(n) {
    // get current date from a service i previously created
    const data = this.dateService.getDate();
    const date = data.split('|')[0];
    const day = data.split('|')[1];
    const month = data.split('|')[2];
    const year = data.split('|')[3];
    const finalUdate = parseInt(`${year}${month}${date}`, 10);
    // initialize some variables
    let salesCounter = 0,
      amountCounter = 0,
      changeCounter = 0,
      changePeople = 0;
    // get list of products from a service
    this.authService.getSales().subscribe(d => {
      // assign the products to the server property
      this.server = d.data;


// loop through the array and get the date for each product
      this.server.forEach(serv => {
        const Sdate = serv.date.split('|')[0];
        const Sday = serv.date.split('|')[1];
        const Smonth = serv.date.split('|')[2];
        const Syear = serv.date.split('|')[3];
        const finalServerDate = parseInt(`${Syear}${Smonth}${Sdate}`, 10);

        // subtract the each product date from the user date
        const calcResult = finalUdate - finalServerDate;


        if (calcResult === n) {
          // if the calc result is = n ( n is a number between 7 and 0 to symbolize days of the week)
          const daySales = this.daySales(salesCounter);
          salesCounter = daySales;

          amountCounter = amountCounter + serv.price;
          if (serv.change > 0) {
            changeCounter = changeCounter + serv.change;
            const change = this.countChange(changePeople);
            changePeople = change;
          }
        }

      });
      const processedData = {
        salesCounter: salesCounter,
        amountCounter: amountCounter,
        changeCounter: changeCounter,
        changePeople: changePeople
      };
      this.processedData = processedData;
    });
    return this.processedData;
  }
  daySales(salesCounter) {
    let LsalesCounter = salesCounter;
    LsalesCounter++;
    return LsalesCounter;
  }

  countChange(changePeople) {
    let LchangeCounter = changePeople;
    LchangeCounter++;
    return LchangeCounter;
  }
  returnData(n) {
    return this.getSalesCounter(n);
  }
}

0 个答案:

没有答案