ngx-translate在含离子4的设备上不起作用

时间:2019-04-09 14:15:50

标签: angular typescript ionic-framework ionic4

我正尝试在我的ngx-translate项目中使用Ionic 4,我已经遵循this guide。它可以在我的浏览器中很好地工作,但是当我在Android设备上进行构建和测试时,它无法翻译。

我已经使用npm安装了它,然后将其添加到导入中,创建了函数,并将标签添加到了HTML中。

这是我的密码

使用以下方式安装:

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();
      }
}

在我创建的assets/i18n/文件中:

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"
    }
}

ar.json

{
    "menu": {
        "home": " الرئيسية",
        "buy_dress": "شراء / إستئجار",
        "add_dress": "إضافة فساتين للبيع اوالإيجار",
        "register": "إنشاء حساب جديد",
        "login": "تسجيل الدخول",
        "my_ads": "إعلاناتى",
        "logout": "تسجيل الخروج"
    },
    "home": {
        "other_language": " English",
        "buy_dress": "شراء / إستئجار",
        "add_dress": "إضافة الفساتين"
    }
}

最后是我添加HTML文件的方式:

<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>

在浏览器中可以很好地工作,但是当我将其内置到Android设备中时,它会显示home.add_dress之类的字词,而不是呈现它。

1 个答案:

答案 0 :(得分:1)

这可能是因为手机存储空间没有值,并且在以下函数中返回undefined

this.storage.get('current_language').then((val) => {
  console.log(val);
  this.language = val;
  this.translate.setDefaultLang(this.language);
});

您可能希望添加if语句,以避免出现以下情况:

this.storage.get('current_language').then((val) => {
  console.log(val);
  if(val)
  {
     this.language = val;
  }
  this.translate.setDefaultLang(this.language);
});

请原谅我,如果这没有帮助,祝你好运。