简体   繁体   中英

Binding a typescript variable to translate service

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 ?

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);

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM