0

I have the following method, the value inside subscribe is correct, but outside of the subscribe scope, it is blank.

getTranslation(text: string): string {
  var translatedText: string = "";
  this.translate.get(text).subscribe((text: string) => {
  translatedText = text;
  alert(translatedText);
 });
  alert(translatedText);
  return translatedText;
 }
avdeveloper
  • 449
  • 6
  • 30
  • 2
    Does this answer your question? [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Yehor Androsov Dec 04 '20 at 06:24

1 Answers1

0

subscribe is probably an asynchronous function. There's no way to get the value from subscribe and move it to the outer scope synchronously because you don't know how long it'll take until the callback is called.

In order to return a value you have to make the getTranslation method asynchronous as well by returning a promise.

Move your existing code inside of the callback for subscribe

function getTranslation(text: string): string {
  return new Promise(async (resolve) => {
    this.translate.get(text).subscribe((text: string) => {
      resolve(text);
    });
  });
}

Abir Taheer
  • 2,502
  • 3
  • 12
  • 34