Deniss M. Deniss M. - 2 months ago 27
TypeScript Question

ngx-translate with angular material 2 MdSnackBar

I'm new to TS and Angular 4. I need to be able to show a user a translated

CLOSE
word inside the angular material 2
MdSnackBar
. I've understood that you can call the ngx-translate translation service from within the code like this:

this.translate.get('ERROR.CLOSE').subscribe((res: string) => {
console.log(res);
});


The thing is that I need to be able to show this inside an angular material 2 element called
MdSnackBar
.

I wanted to execute it like this:

this.snackBar.open(error, this.getCloseWord(), {
duration: 10000,
})

private getCloseWord() {
this.translate.get('ERROR.CLOSE').subscribe((res: string) => {
console.log(res);
});
}


But I don't know how to make the
getCloseWord()
method to return a correct string value out of an observable.

Answer Source

Try as follow:

public someMethod() {
  const error = ...some error...;
  ...
  this.translate.get('ERROR.CLOSE').subscribe(( res: string ) => {
    this.snackBar.open(error, res, { duration: 10000 });
  });
  ...
}

The ".get()" function returns an Observable so just open your snackbar when "get" is subscribed. Then you know that your translation is available.


A solution with more than one observer could be as follows:

public someMethod() {
    const newObserver = new ReplaySubject();
    let error = null;
    let close = null;

    this.translate.get('ERROR.MESSAGE').subscribe( (translation: string) => {
        error = translation;
        newObserver.next();
    });

    this.translate.get('ERROR.CLOSE').subscribe( (translation: string) => {
        close = translation;
        newObserver.next();
    });

    newObserver.subscribe( () => {
        if(error && close) {
            this.snackBar.open(error, close, { duration: 10000 });
        }
    });
}