Wait for method to execute then execute the next code in angular

Viewed 76

I am trying to use the requestDetails variable outside the subscribe method but its showing "undefined"

service.ts

  requestDetails$ = new Subject<any>();
  updateApprovalMessage(message: string) {
  this.requestDetails$.next(message)
  }

component.ts

requestDetails:any

this.technicalRequestService.requestDetails$.subscribe(data=>{
this.requestDetails=data
console.log(this.requestDetails)
//here it is printing
}
console.log(this.requestDetails)
//but its is showing undefined
1 Answers

Notice how undefined is logged first?

That's because your callback function hasn't been called yet. If you want to execute code after this.requestDetails=data, you will have to do so inside the function. You can of course call other methods from here as well.

ngOnInit() {
  this.technicalRequestService.requestDetails$.subscribe(data=>{
    this.requestDetails=data;
    console.log(this.requestDetails);
    afterSettingRequestDetails();
  }
}

afterSettingRequestDetails(){
  console.log(this.requestDetails);
}

Or if you prefer async / await

async ngOnInit() {
  this.requestDetails = await firstValueFrom(this.technicalRequestService.requestDetails$);
  console.log(this.requestDetails);
}

But this will only fire once, useful for single requests but not data streams.

Related