0

In my Angular project I'm trying to set translated value to html via ngx-translate. I receive the key of value dynamically and trying to get the value with get method of TranslateService, set it to component variable and then render to html

@Component({
  selector: 'app-courses',
  templateUrl: './courses.component.html',
  styleUrls: ['./courses.component.scss']
})
export class CoursesComponent implements OnInit{

  value: string;
  constructor(private translate: TranslateService) { }

  ngOnInit() {
  }

 getTranslateByKey(key) {
  let subject = new Rx.BehaviorSubject('');
  this.translate.get(key).subscribe(v => this.value = v);
}

The problem is that inside subscribe method it's not working; I read at https://stackoverflow.com/questions/37089977/how-to-get-current-value-of-rxjs-subject-or-observable#:~:text=If%20you%20want%20to%20have,to%20get%20the%20current%20value that it can be solved via BehaviorSubject, but don't understand how to use it in my case.

Iliya Gaponov
  • 39
  • 1
  • 1
  • 7
  • Hello, why don't you use translate pipe in your template? For example `key | translate`. In that case you don't need BehaviourSubject, I think. If you have your translations preloaded you can use simply `this.value = this.translate.instant(key)` this method returns you translation by key syncronously. – Max Ivanov Jul 23 '20 at 22:08
  • I tried this but it's returned the key and not a value. Don't know the reason – Iliya Gaponov Jul 23 '20 at 22:59
  • It is return key if key doesn't exists in key store. Have you done something similar `this.translate.setTranslation(langCode, translationsConfig)`? – Max Ivanov Jul 24 '20 at 07:41

0 Answers0