i have some kind of problem. I found many similar problems on stack overflow but nothing resolved my problem... I want to translate the language in Ionic/Angular and I have to fetch it from a database.
When I am loading the application many components getting initialized and obviously many values need to get showed in frontend in the right language. In my initial Version I called the DB every time I needed a word, so in initialization I hat about 40 request with one word the the db. -> than I made a buffer in the language Service for 50ms and created an array for the http(s) call. I reduced the calls from 40 requests to 1-2 calls onLoad the application.
Simple explanation:
//language.service.ts
languageSub = new BehaviorSubject<any>(null);
cache = []; // this is global
pseudocode
getLanguage(shortcut: string[]) {
{{code that makes an array with set timeout and saves to global cache array}}
if(cache.length > 0){
return this.http.get<language[]>(`${services.language.apiUrl}/textbaustein`, { params })
.subscribe(data => {
let temp = {};
data.forEach(element => {
temp[element.shortcut] = element.text;
}
this.languageSub.next(temp);
}
}
in my angular Template I have this simple Pipe
{{ value | translatePipe }}
Since the Service does not immediately respond (which would not work because of the buffering) I created a BehaviorSubject, which emits Data after it got the answer from the http call. The language Pipe (and here the horror begins) needs to wait for the subject to response, otherwise he has only undefined.
//language.pipe.ts
constructor(private languageService: LanguageService) { }
transform(value: string): Subscription<string> {
this.languageService.getLanguage([value]); //this makes the languageService add a value to the global cache array and then call the server
return this.languageService.languageSub.subscribe(data => {
console.log(data);
if (data != null) { //on init the data will be null
if (data[value] != undefined || data[value] != null) {
console.log(data[value]);
return data[value]; //the value gets perfectly logged in console, but never arrives in frontend
}
}
})
}
this does not work the way I want, but I have also no clue how to get it to work in a pretty way (I have already subscribed this BehaviorSubject in every Component and deleted the Pipe, but it creates muuuuch lines of code and looks ugly). I do not want to remove the buffering from the Service, because if more users use the application there would me many "unnecessary" calls.
Does somebody know how to fix this?