angularng2-translate

angular 2 ng2-translate custom TranslateLoader not working with API


ng2-translate not working with custom TranslateLoader when fetching data from API. Below is my custom TranslateLoader

translateCustomLoader.ts

@Injectable()
export class CustomTranslateLoader implements TranslateLoader  {

    constructor(private http: Http, private apiService: AuthHttp) { console.log("customer loader initialized"); }

    getTranslation(lang: string): Observable<any>{
        var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;

        return this.apiService.get(apiAddress).map((res) => res.json());

        //return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});
    }
}

Response from API is

{ "hello": "translatedhello","welcome":"translatedwelcome"}

Added TranslateLoader to providers in app.module.ts

providers: [CustomTranslateLoader, { provide: TranslateLoader, useClass: CustomTranslateLoader}]

In my HTML page I have below

<h4>{{ 'hello' | translate }}</h4>

I still see hello getting rendered.This works fine if I replace

return this.apiService.get(apiAddress).map((res) => res.json());

with

return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});

So I am pretty sure there isn't anything wrong with the configuration.What am I missing here?


Solution

  • I got it working by changing getTranslation as below

    getTranslation(lang: string): Observable<any> {
        var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;
        return Observable.create(observer => {
                this.authService.get(apiAddress)
                    .subscribe((res: Response) => {
                        observer.next(JSON.parse(res.json()));
                        observer.complete();               
                    });
            });
    
        }
    

    Although doesn't make much sense to me. Hope this helps someone.