Home > Software design >  get Data outside subscribe method in angular 13
get Data outside subscribe method in angular 13

Time:12-01

I have 2 functions in ngOninit

ngOnInit(){
  this.getRowData();
  this.getWrapperGridData(); 
}

GetRowData() is used to subscribe to a service and it looks like this

  getRowData() {
  this.showDataServiceSubscription = this.heroService.showData().subscribe((data) => {
    this.onlineData = data;
  console.log('onlineData 1',this.onlineData);

  })
}

In getWrapperGridData, I am calling this.onlineData again like this

  getWrapperGridData(){
    console.log('onlineData',this.onlineData);
  }

The problem is I am getting the result of onlineData inside getRowData method as it is written inside subscribe but I am getting undefined inside getWrapperGridData. How do we fix this?

CodePudding user response:

it depend on what you want to do inside getWrapperGridData ( right now you only log it to console )

you can use rxjs pipe like this to manipulate the data return from the showData method.

 getRowData() {
   this.showDataServiceSubscription = 
       this.heroService.showData()
        .pipe(tap(data => {
           // here you can do what you plan to to do inside getWrapperGridData
          }))
        .subscribe((data) => {
          this.onlineData = data;
       console.log('onlineData 1',this.onlineData);

   })
 }

--> it's not a best practice to subscribe inside the .ts file, instead considered store the Observable itself inside the variable, for example

 this.onlineData$ = this.heroService.showData();

and use async pipe, see Docs

CodePudding user response:

The problem you face is that the calls to getRowData and getWrapperGridData respectively are synchronous, the call to the backend and retrieval of the data is asynchronous though. That means by the time getWrapperGridData is executed, getRowData and data fetching is likely not done yet. Because getWrapperGridData seems to depend on the data of getRowData you can chain the calls together using rxjs switchmap. The two backend calls will then be chained and executed one after another.

Note: Inside switchMap you need to return an Observable. I assume that you need to fetch data asynchronously inside getWrapperGridData. If that is not the case, use tap instead of switchMap.

import { switchMap } from 'rxjs/operators';

export class Foo implements OnInit {
  ngOnInit(){
    this.getData();
  }
  
  getData() {
    this.heroService.showData().pipe(
      switchMap((onlineData) => {
        this.onlineData = onlineData; // In case you need this globally

        return this.gridWrapperService.getData(onlineData);
      })
    ).subscribe((gridWrapperData) => {
      // Deal with the data.
    })
  }
}
  • Related