I have the following service:
// transloco-loader.ts
import { inject, Injectable } from '@angular/core';
import {TranslocoLoader } from '@ngneat/transloco';
import { map, take} from 'rxjs';
import { CFV2 } from '@go/shared-data-access-angular-config';
@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
private _configFacade = inject(CFV2.ConfigFacade);
getTranslation(lang: string) {
// We always get here
console.log('function gets called each time');
return this._configFacade.configState$.pipe(
take(1),
map((state) => {
// But not here! Although configState$ didn't change!
console.log('But we get here ONLY ONCE!');
return { t: 'something' };
}),
);
}
}
If I call getTranslation
method 2 times, only the first time it goes into the pipe! Am I missing something here? I'm using Angular 17.
I could actually manage to fix the issue by using the async syntax:
async getTranslation(lang: string): Promise<{ t: string }> {
console.log('function gets called each time');
const state = await firstValueFrom(
this._configFacade.configState$.pipe(take(1)),
);
console.log('And we get here each time too!');
return { t: 'something' };
}
But I'm still wondering why it didn't work by rxjs Observables syntax!
I figured it out! It was as easy as ABC! When I was actually using the Transloco Service load
method (to eventually call getTranslation
method on the Transloco loader service) I had to subscribe to it:
private readonly _langService = inject(TranslocoService);
this._langService
.load('en')
.pipe(take(1))
.subscribe();
Calling the load
method alone, won't go to the map
operator, as we don't subscribe to it! But async function was working, because await fetches the results first, and then continues...