如何使用ngx-translate从子事件向父事件

时间:2018-10-05 05:30:51

标签: angular angular-directive

我使用ngx-translate制作多语言的网状网页。我将JSON文件用于语言,并将它们放在资产/ i18n / en.json(对于英语)中,以及资产/ i18n / ge.json对于德语。我实现了从孩子到父母的EventEmit事件,如下所示:

child.component.ts:

private translateService: TranslateService;
@Output() showLanguage = new EventEmitter();

constructor(translateService: TranslateService) {
    this.translateService = translateService;
    this.translateService.setDefaultLang('en');
  }



 switchLanguage(language: string) {
    this.showLanguage.emit(this.translateService.use(language));
  }

Child.html

  <button (click)="switchLanguage('en')">en</button>
  <button (click)="switchLanguage('fr')">fr</button>

parent.component.ts

private translateService: TranslateService;
 constructor(translateService: TranslateService) {
    this.translateService = translateService;
  }
switchLanguage(language) {
    this.translateService.use(this.language);
 }

Parent.html

  <child-page (showLanguage)="switchLanguage($event)"><child-page>

App.module.ts

 export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
  }

  @NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})

但是当我单击“角度”按钮时,会抛出错误:

ERROR TypeError: Object(...) is not a function
    at TranslateService.use (ngx-translate-core.js:555)
    at ChildComponent.switchLanguage (childcomponent.component.ts:40)
    at Object.eval [as handleEvent] (ChildComponent.html:12)
    at handleEvent (core.js:13589)
    at callWithDebugContext (core.js:15098)
    at Object.debugHandleEvent [as handleEvent] (core.js:14685)
    at dispatchEvent (core.js:10004)
    at eval (core.js:10629)
    at HTMLButtonElement.eval (platform-browser.js:2628)
    at ZoneDelegate.invokeTask (zone.js:398)
    at Object.onInvokeTask (core.js:4751)
    at ZoneDelegate.invokeTask (zone.js:397)
    at Zone.runTask (zone.js:165)
    at HTMLButtonElement.ZoneTask.invoke (zone.js:460)

请帮助我。谢谢

1 个答案:

答案 0 :(得分:0)

代替

switchLanguage(language: string) {
this.showLanguage.emit(this.translateService.use(language));
}

尝试仅发出语言

switchLanguage(language: string) {
this.showLanguage.emit(language);
}