Home > Back-end >  Binding a typescript variable to translate service
Binding a typescript variable to translate service

Time:07-09

I'm trying to have a TypeScript variable bind to the translate service just like binding in the HTML markup, which works fine.

Here's what I've tried so far

ngOnInit() {

    this.customTranslateService.get("mainLayout.userProfileDropdown.changeLocale").subscribe((result) => {
      this.changeLocaleText = result;
    })

    this.customTranslateService.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.changeLocaleText = this.customTranslateService.instant("mainLayout.userProfileDropdown.changeLocale");
    });

    this.userProfileMenuOptions = [
      {
        text: this.changeLocaleText, itemId: "LocaleSelect"
      },
      {
        text: "Report a bug", itemId: "BugReport"
      },
      {
        text: "Request a feature", itemId: "FeatureRequest"
      },
      {
        text: "Log Out", itemId: "LogOut"
      }
    ];

  }

customTranslateService is just a service that wraps TranslateService.

The first subscription works ok, but when I switch languages, the onLangChange does trigger, changing the variable content correctly, but userProfileMenuOptions's reference to changeLocaleText is not binded therefore not updated.

Using a BehaviorSubject can't really be done here as it is typescript code, not html markup that can use the async pipe.

Maybe recreating the userProfileMenuOptions array everytime the language change subscription is called could be an option, although I'm not sure the component that uses the array will like it.

PS: instant will work here because I have an application loader that loads all available languages before the application is available to the user.

Any ideas ?

CodePudding user response:

ngOnInit() {

    this.customTranslateService.get("mainLayout.userProfileDropdown.changeLocale").subscribe((result) => {
      this.changeLocaleText = result;
    })

    const getUserPorfileMenuOptions = (changeLocaleText: string) => {
      return [
        {
          text: this.changeLocaleText, itemId: "LocaleSelect"
        },
        {
          text: "Report a bug", itemId: "BugReport"
        },
        {
          text: "Request a feature", itemId: "FeatureRequest"
        },
        {
          text: "Log Out", itemId: "LogOut"
        }
      ];
    }

    this.customTranslateService.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.changeLocaleText = this.customTranslateService.instant("mainLayout.userProfileDropdown.changeLocale");
      this.userProfileMenuOptions = getUserPorfileMenuOptions(this.changeLocaleText);
    });

    this.userProfileMenuOptions = getUserPorfileMenuOptions(this.changeLocaleText);

  }
  • Related