我接管了Ionic v2的小型应用程序的代码,并且我使用ng2-translate
进行翻译。我只在模态窗口中有翻译问题。它在任何地方都能很好地工作,除了这个模态,我只能看到转换键。
这是我的AppModule
:
@NgModule({
declarations: [
MyApp,
// ...
SearchPersonModal
],
imports: [
IonicModule.forRoot(MyApp),
ChartModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
// ...
SearchPersonModal,
],
providers: [
ApiCaller
]
})
export class AppModule {}
模式在应用程序中用于搜索远程数据库中的用户。这是模态组件的代码:
@Component({
selector: 'page-search-person',
templateUrl: 'search-person.html',
})
export class SearchPersonModal {
public caller : ApiCaller = null;
public translate : TranslateService = null;
// ..
constructor(
public viewCtrl: ViewController,
public toastr: ToastController,
params: NavParams
) {
this.translate = params.get('translate');
this.caller = params.get('caller');
}
// ...
}
以下是模态的呈现方式:
let modal = this.modalCtrl.create(SearchPersonModal, {
caller: this.caller,
translate : this.translate
});
我认为代码的作者将服务作为参数传递,因为依赖注入不起作用。事实上,当我尝试这样做时,使用这个构造函数:
export class SearchPersonModal {
//public caller : ApiCaller = null;
//public translate : TranslateService = null;
// ...
constructor(
public viewCtrl: ViewController,
public toastr: ToastController,
public caller: ApiCaller,
public translate: TranslateService,
params: NavParams
) {
//this.translate = params.get('translate');
//this.caller = params.get('caller');
}
// ...
}
翻译仍然不起作用,但ApiCaller
服务按预期工作。为什么这项服务运作良好,而不是翻译呢?
答案 0 :(得分:2)
这似乎是currently known issue with Ionic 2 and has been reported on their repo。解决方法是需要为问题日志中所述的模态重新初始化翻译服务:
事情在页面上起作用,但在模态中不起作用。就好像翻译服务在模态中不可用。如果,在模态中,我通过运行this.translate.use('fr')重新初始化翻译服务;事情很好。例如,以下代码可以正常工作。
import { TranslateService } from 'ng2-translate/ng2-translate';
@Component({
templateUrl: 'my-modal.html',
selector: 'my-modal',
})
export class MyModal {
constructor(
private translate: TranslateService
) {
var self = this;
this.translate.use('fr'); // Re-initializing the translate service inside a modal
// Here on translation works fine
}
}
因此,映射到当前实现的此变通方法应与此类似:
import { TranslateService } from 'ng2-translate/ng2-translate';
export class SearchPersonModal {
public caller : ApiCaller = null;
public translate : TranslateService = null;
// ...
constructor(
public viewCtrl: ViewController,
public toastr: ToastController,
public caller: ApiCaller,
private translate: TranslateService
params: NavParams
) {
this.caller = params.get('caller');
this.translate.use('en'); // Re-initialised rather than passed via navParams.
}
// ...
}