I have a function using the library ngx-translate which returns an observable. So to use it I subscribe to the method and get the value I need. After that I want to do a return but I would like that the return happen after the value has been gotten.
This is my code:
test(textePage: string[], params?: Object){
let textToSpeech: string;
this._translateService.get(textePage).subscribe(res => {
textToSpeech = (Object.keys(res).map(e=>res[e])).join('');
});
return textToSpeech;
}
I would like something like:
test(textePage: string[], params?: Object){
let textToSpeech: string;
this._translateService.get(textePage).subscribe(res => {
textToSpeech = (Object.keys(res).map(e=>res[e])).join('');
return textToSpeech;
});
}
But I know it is not the best way.
Thanks a lot.
You can use Observable methods like map
:
return this._translateService.get(textePage).pipe(
map(res => (Object.keys(res).map(e=>res[e])).join(''))
);
Now in order to use this you will have to call this.test(textePage, params).subscribe
in your component to set the property of the component. You can also use the | async
pipe which will handle the subscription for you.