0
import {TranslateService, LangChangeEvent} from "@ngx-translate/core";
class ExportLanguageFun {
    public currentLang : string;
    constructor(private translate : TranslateService) {  
    }
    public static setValue(): string {
        this.translate
        .onLangChange
    .subscribe(lang => {
     this.currentLang = lang;
    })
    return this.currentLang;
        }
    }

export let exportLanguage = ExportLanguageFun.setValue(); //Error: Property 'setValue' does not exist on type 'typeof ExportLanguageFun'.

Expected output console.log(let+"someValue");

rebello
  • 67
  • 1
  • 6
  • You're using an observable, which will watch for new values to assign this.currentLang the value of lang. You return this.currentLang outside of the observable. Since javascript runs asynchronously, it won't necessarily wait for this.currentLang to have a new value before updating. What are you trying to accomplish here? – Notmfb Nov 15 '17 at 20:44
  • yes I am using a observable. I am trying to set a value to this.currentLang which is coming from the API. Need to return the value this.currentLang. – rebello Nov 15 '17 at 20:46
  • Right, you can't return the value outside of the subscribe function. It won't work. Generally, you'd do something with the 'lang' variable each time it updates, so returning it probably isn't the best way to handle this, because each time you try to access the data by calling setValue(), you'll be resubscribing. This will eat up memory. I'm writing up an answer below that might help. – Notmfb Nov 15 '17 at 20:55

1 Answers1

0

You should rethink your structure here. What you want returned here is the lang from inside the observable. You need to restructure what you are doing here.

public static setValue(): string {
    return this.translate.onLangChange
}

Then when you call the function you could subscribe to it and do something with it there.

this.setValue().subscribe(lang => {
  this.currentLang = lang;
  // do something else with it
})

By subscribing, each time there is a new value, the function will run. Instead of trying to return the value just do something with it with each change, wherever you subscribe to it.

Notmfb
  • 491
  • 3
  • 8