Issue
I'm trying to use ngx-translate
with my Ionic 4
project, I've followed this guide. It works great in my browser, but it fails to translate when I build and test on my android device.
I've installed it using npm
then added to imports, created the functions and added the tags to my HTML.
Here are my codes
Installed using:
npm install @ngx-translate/core @ngx-translate/http-loader --save
app.module.ts
:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RouteReuseStrategy} from '@angular/router';
import {IonicModule, IonicRouteStrategy} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {AppComponent} from './app.component';
import {AppRoutingModule} from './app-routing.module';
import {CallNumber} from '@ionic-native/call-number/ngx';
import {Camera} from '@ionic-native/camera/ngx';
import { AuthServiceService } from './auth-service.service';
import { IonicStorageModule } from '@ionic/storage';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
HttpClientModule,
AppRoutingModule,
IonicStorageModule.forRoot(),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
],
providers: [
StatusBar,
SplashScreen,
CallNumber,
Camera,
{provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
AuthServiceService,
],
bootstrap: [AppComponent]
})
export class AppModule {
}
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
app.component.ts
:
import {Component} from '@angular/core';
import { Storage } from '@ionic/storage';
import {Platform} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import { AuthServiceService } from './auth-service.service';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['main.scss'],
})
export class AppComponent {
language = 'en';
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private storage: Storage,
private authService: AuthServiceService,
private translate: TranslateService // add this
) {
this.initializeApp();
}
public appPages = [
{
title: 'Home',
url: '/home',
icon: 'home'
},
{
title: 'Buy / Rent a Dress',
url: '/list',
icon: 'woman'
},
{
title: 'Add Dress for Sale/Rental',
url: '/add-dress',
icon: 'add'
},
{
title: 'Register New Account',
url: '/create-account',
icon: 'person-add'
},
{
title: 'Login to your account',
url: '/login',
icon: 'log-in'
},
];
initializeApp() {
this.platform.ready().then(() => {
this.storage.get('current_language').then((val) => {
console.log(val);
this.language = val;
this.translate.setDefaultLang(this.language);
});
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
authenticatedState() {
return this.authService.authenticated();
}
logUserOut() {
return this.authService.logout();
}
}
home.page.ts
:
import {Component} from '@angular/core';
import { AuthServiceService } from '../auth-service.service';
import { Storage } from '@ionic/storage';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from '@angular/common/http';
import {HttpHeaders} from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
private language = 'en';
token: Observable<any>;
tokens: Observable<any>;
current_token = '';
constructor(public authService: AuthServiceService, private storage: Storage, public httpClient: HttpClient,
private translateService: TranslateService, ) {
this.storage.get('current_language').then((val) => {
this.language = val;
});
const login_data = {
'username': 'myusername',
'password': 'mypassword',
};
this.token = this.httpClient.post('myurl', login_data);
this.token.subscribe(token_data => {
console.log('my data: ', token_data);
this.token = token_data;
this.current_token = this.token['token'];
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': String('Token ' + this.current_token)
})
};
this.tokens = this.httpClient.get('myurl', httpOptions);
this.tokens.subscribe(data => {
this.tokens = data;
console.log('my data: ', data);
storage.get('the_token').then((val) => {
const the_current_token = val;
console.log('saved token is ', val);
// tslint:disable-next-line: forin
for (const obj in this.tokens) {
const the_list = this.tokens[obj]['key'];
if (the_list === the_current_token) {
this.authService.login();
} else {
}
}
});
});
storage.get('user_id').then((val) => {
console.log('saved user_id is ', val);
});
});
}
loginUser() {
this.authService.login();
console.log(this.authService.authenticated());
}
logoutUser() {
this.authService.logout();
console.log(this.authService.authenticated());
}
isAuthenticated() {
console.log(this.authService.authenticated());
return this.authService.authenticated();
}
languageChange(lang) {
console.log(this.language);
this.storage.set('current_language', lang);
this.language = lang;
this.translateService.setDefaultLang(this.language);
window.location.reload();
}
}
in the assets/i18n/
I've created to files:
en.json
:
{
"menu": {
"home": " Home",
"buy_dress": "Buy / Rent a Dress",
"add_dress": "Add Dress for Sale/Rental",
"register": "Register a new account",
"login": "Login to your account",
"my_ads": "My Ads",
"logout": "Logout"
},
"home": {
"other_language": " العربية",
"buy_dress": "Buy / Rent ",
"add_dress": "Add Dress"
}
}
and ar.json
:
{
"menu": {
"home": " الرئيسية",
"buy_dress": "شراء / إستئجار",
"add_dress": "إضافة فساتين للبيع اوالإيجار",
"register": "إنشاء حساب جديد",
"login": "تسجيل الدخول",
"my_ads": "إعلاناتى",
"logout": "تسجيل الخروج"
},
"home": {
"other_language": " English",
"buy_dress": "شراء / إستئجار",
"add_dress": "إضافة الفساتين"
}
}
and finally here is how I added my HTML file :
<ion-header>
<ion-toolbar color="medium">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Fostania
</ion-title>
<ion-button color='medium' slot='end' (click)='languageChange("ar")'
*ngIf='language === "en";else arabic_button'>
<small>
{{ 'home.other_language' | translate }}
<ion-icon name='globe'></ion-icon>
</small>
</ion-button>
<ng-template #arabic_button>
<ion-button color='medium' slot='end' (click)='languageChange("en")'>
<small>
{{ 'home.other_language' | translate }}
<ion-icon name='globe'></ion-icon>
</small>
</ion-button>
</ng-template>
</ion-toolbar>
</ion-header>
<ion-content padding>
<img src='../assets/imgs/logo.png'>
<div align='center' style="opacity: 0.7;">
<ion-button color='medium' style="height: 120px;" routerLink='/list'><img src='../assets/imgs/dress.png'
style="width: 100px; height: 80px;">
{{ 'home.buy_dress' | translate }}
</ion-button>
<ion-button color='medium' style="height: 120px;" routerLink='/add-dress'><img src='../assets/imgs/add.png'
style="width: 100px; height: 80px;">
{{ 'home.add_dress' | translate }}
</ion-button><br>
</div>
</ion-content>
in the browser, it works great, but when I build into my android device it shows the words like home.add_dress
instead rendering it.
Solution
This might be because the phone storage has no value and returns undefined in the below function
this.storage.get('current_language').then((val) => {
console.log(val);
this.language = val;
this.translate.setDefaultLang(this.language);
});
You may want to add if statement to avoid that as below:
this.storage.get('current_language').then((val) => {
console.log(val);
if(val)
{
this.language = val;
}
this.translate.setDefaultLang(this.language);
});
Answered By - Tariq Saeed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.