Value returned before assigned in subscribe

Viewed 42

I need to return a value from subscribe since I cannot set in a global variable. However, the function always returns before the value is assigned the data from the subscribe. I tried all the answers suggested in posts in the topic but it didn't work

getMessage(field): string {
  this.service.getMessage(field).subscribe(mssg => {
    let message = '';
    message = mssg;
    return message;
  });
}

The calling function: (It's called several times in the component) it's inside setting values for angular material table

something like


    const ELEMENT_DATA: PeriodicElement[] = [
      {position: 1, name: data?
this.getMessage(obj) + ' ' + someobj.id
, weight: 1.0079, symbol: 'H'},
      {position: 2,  name: ess?
this.getMessage(se) + ' ' + yy.gt, weight: 4.0026, symbol: 'He'},
    ,
    ];
2 Answers

You have not understood well how this works.

Your return statement returns the value in the subscribe function. It does not return the value in the function. Actually, your function returns void.

You have no way of returning an asynchronous value synchronously.

What you should do instead is this :

getMessage(field): Observable<string> {
  return this.service.getMessage();
}

// Somewhere else

this.getMessage('myField').subscribe(() => {
  // Do what you want here
});

Just to complete possible options: You can also "convert" your observable to a promise using lastValueFrom from rxjs package (only makes sense if your observable is only emitting one value) and using an async function (which can be "awaited" by the consumer):

async getMessage(field): Promise<string> {
  return lastValueFrom(this.service.getMessage(field));
}
Related