How to return list inside subscribe Angular

352 Views Asked by At
winServiceInfo() {
    this.dataArrs=[]
    this.winServiceURL = JSON.parse(this.WinService[0].windowsServicesInfo)["Stactuscheck"];
    this.service.getWinServicesInfo(this.winServiceURL)
    .pipe(
      catchError(this.handleError)
    )
    .subscribe((data: any) => {
        this.setSubscribeData(data);
        console.log(this.dataArrs)
    });
    console.log(this.dataArrs)
    return this.dataArrs;
}

setSubscribeData(data): any {
    this.WinService = data.windowsServicesInfo;
    this.dataArrs = this.getKeyValJsonObj();
return this.dataArrs;
}

the first console.log(this.dataArrs) retuens Arrar(3) but the second console.log(this.dataArrs) returns Arrar(0). I understand that subscribe is an asynchronous operation and for that reason.

So how to handle the situation to return the Array(3) from second console.log(this.dataArrs)

1

There are 1 best solutions below

5
Eli Porush On

instead of subscribing inside the function you need to return the Observable

this.dataArrs = winServiceInfo() {
  this.winServiceURL = 
  JSON.parse(this.WinService[0].windowsServicesInfo)["Stactuscheck"];
  return this.service.getWinServicesInfo(this.winServiceURL)
     .pipe(
        catchError(this.handleError)
          );
}

and in your template:

<tr *ngFor="let opc of dataArrs | async"> <tr>

and however call this function can subscribe to get the data