0

I want to have an exported function that returns a string, but I can't make it work, because I have a subscribe inside the function.

export function translateBreadcrumbSelf(key: string): string {
  this.translateService.get(key).subscribe(
    (result: string) => {
      return result;
    }
  );
}

How can I return the result string? I understand that this is an async call, so is it even possible to do this?

Tamas Koos
  • 53
  • 1
  • 3
  • Looks like this has been previously asked - https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe – Anthony Liriano Aug 14 '18 at 13:55
  • 5
    Possible duplicate of [angular 2 how to return data from subscribe](https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe) – karoluS Aug 14 '18 at 13:56
  • [Welcome to stackoverflow please visit Help Center before asking](https://stackoverflow.com/help) . Please do some research before asking there is highest chances the particular problem have solved before if didn't the community will always help. – Ram Chandra Neupane Aug 14 '18 at 14:03

1 Answers1

0

Do not subscribe until you needed.

// yourOtherFile
export function translateBreadcrumbSelf(key: string): string {
  this.translateService.get(key);
}

// thisFile
import { translateBreadcrumbSelf } from "yourOtherFile";
translateBreadcrumbSelf.subscribe(
    (result: string) => {
      console.log(result);
    }
  );
Luillyfe
  • 6,183
  • 8
  • 36
  • 46