Estou usando o i18n no angular, como imagem abaixo:
No app.component.ts está assim:
import { Component } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
public translate : any;
constructor(translate: TranslateService) {
translate.addLangs(["pt", "en"]);
translate.setDefaultLang("pt");
const browserLang = translate.getBrowserLang();
translate.use(browserLang.match(/pt|en/) ? browserLang : "pt");
}
}
Para chamar o que está descrito no in8, faço assim no html:
<span>{{ 'SISTEMA' | translate }} {{ 'NOME_DO_SISTEMA' | translate }}</span>
No json do inglês está assim:
{
"NOME_DO_SISTEMA": "from medical clinic",
}
No json do português está assim:
{
"NOME_DO_SISTEMA": "de clinica médica",
}
Preciso se o usuário mudar a linguagem, muda o arquivo de acordo com a linguagem definida.
Fiz assim:
<select #langSelect (change)=“translate.use(langSelect.value)”>
<option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">
{{ lang }}</option>
</select>
Mas tem erro conforme imagem.
Estou usando @ngx-translate/http-loader.
O que pode ser ?
O component desse html da imagem é o AppComponent
?
Não @Lucas_Camara, é um component criado com o nome menu.
Esse translate tem um module? Se sim, ele está adicionado ao module onde esse componente menu está?
Tenho um comum.module.ts
import { NgModule } from "@angular/core";
import { MaterialModule } from "./material-module/material.module";
import { CommonModule } from "@angular/common";
import {
HttpClientModule,
HTTP_INTERCEPTORS,
HttpClient
} from "@angular/common/http";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { AlertModule } from "ngx-alerts";
import { DialogComponent } from "./dialog/dialog.component";
import { LoaderService } from "./services/loader/loader.service";
import { AuthInterceptor } from "../security/interceptor/auth.interceptor";
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { MenuComponent } from "../componentes/menu/component/menu.component";
import { AppRoutingModule } from "../app-routing.module";
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
imports: [
AppRoutingModule,
CommonModule,
MaterialModule,
FormsModule,
ReactiveFormsModule,
AlertModule.forRoot({ maxMessages: 5, timeout: 5000, position: "right" }),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
declarations: [DialogComponent, MenuComponent],
providers: [
LoaderService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
entryComponents: [DialogComponent],
exports: [
AppRoutingModule,
MaterialModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
AlertModule,
DialogComponent,
HttpClientModule,
TranslateModule
]
})
export class ComumModule {}
e tenho o menu.module.ts
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { ComumModule } from "src/app/core/comum.module";
@NgModule({
imports: [CommonModule, ComumModule]
})
export class MenuModule {}
Entendo que não teria que dar erro
Mas eu acho que, no componente que tu for usar o translate, vc tem que ter isso: public translate : any;
.
Ao fazer isso na sua tela:
<select @langSelect (change)="translate.use(langSelect.value)">
Talvez vc precise declarar a variável: translate
, no componente dessa tela (que vc disse que o menu). Igual vc fez no AppComponent
, nessa parte:
export class AppComponent {
public translate : any;
constructor(translate: TranslateService) {
// ...
}
}
Tente declarar o TranslateService tambem no componente do Menu.
Entendo que já está assim: Translate no angular
Coloquei no inicio do tópico
menuComponent.ts
import { Component } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: "app-menu",
templateUrl: "./menu.component.html",
styleUrls: ["./menu.component.css"]
})
export class MenuComponent {
options: FormGroup;
constructor(fb: FormBuilder) {
this.options = fb.group({
bottom: 0,
fixed: false,
top: 0
});
}
shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h =>
h.test(window.location.host)
);
}
Tente alterar esse MenuComponent
para ficar assim:
import { Component } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: "app-menu",
templateUrl: "./menu.component.html",
styleUrls: ["./menu.component.css"]
})
export class MenuComponent {
options: FormGroup;
public translate: TranslateService;
constructor(fb: FormBuilder, translate: TranslateService) {
this.options = fb.group({
bottom: 0,
fixed: false,
top: 0
});
}
shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h =>
h.test(window.location.host)
);
}
O @Lucas_Camara respondeu o que eu ia falar. Só vou adicionar uma correção:
export class MenuComponent {
// Esta variável é um membro e seu valor é undefined
public translate: TranslateService;
// Esta variável é apenas uma variável local
constructor(translate: TranslateService) {}
}
Do jeito como está, o membro translate
nunca vai receber o valor injetado pela Angular. Para isso vc teria que fazer algo assim:
export class MenuComponent {
// Esta variável é um membro e seu valor é undefined
public translate: TranslateService;
// Esta variável é apenas uma variável local
constructor(translate: TranslateService) {
this.translate = translate;
}
}
Só que isso é completamente desnecessário se vc fizer isso:
export class MenuComponent {
constructor(public translate: TranslateService) {}
}
Acrescentar um modificador de acesso ou a keyword readonly
à um parametro do constructor o transforma automaticamente em um membro da classe.
2 curtidas
Deu estes erros no console do navegador:
core.js:5882 ERROR TypeError: Cannot read property 'getLangs' of undefined
at MenuComponent_ng_container_0_Template (menu.component.html:14)
at executeTemplate (core.js:11937)
at refreshView (core.js:11784)
at refreshDynamicEmbeddedViews (core.js:13149)
at refreshView (core.js:11807)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
at refreshView (core.js:11836)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
defaultErrorLogger @ core.js:5882
handleError @ core.js:5935
(anonymous) @ core.js:42716
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41113
tick @ core.js:42713
_loadComponent @ core.js:42753
bootstrap @ core.js:42679
(anonymous) @ core.js:42271
_moduleDoBootstrap @ core.js:42267
(anonymous) @ core.js:42222
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41277
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
(anonymous) @ zone-evergreen.js:851
invokeTask @ zone-evergreen.js:400
onInvokeTask @ core.js:41255
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42252
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:13
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
core.js:40471 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
core.js:5882 ERROR TypeError: Cannot read property 'getLangs' of undefined
at MenuComponent_ng_container_0_Template (menu.component.html:14)
at executeTemplate (core.js:11937)
at refreshView (core.js:11784)
at refreshDynamicEmbeddedViews (core.js:13149)
at refreshView (core.js:11807)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
at refreshView (core.js:11836)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
defaultErrorLogger @ core.js:5882
handleError @ core.js:5935
(anonymous) @ core.js:42716
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41113
tick @ core.js:42713
(anonymous) @ core.js:42553
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41277
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41052
next @ core.js:42550
schedulerFn @ core.js:36880
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36842
checkStable @ core.js:41191
onHasTask @ core.js:41298
hasTask @ zone-evergreen.js:420
_updateTaskCount @ zone-evergreen.js:441
_updateTaskCount @ zone-evergreen.js:264
runTask @ zone-evergreen.js:185
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42252
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:13
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
core.js:5882 ERROR TypeError: Cannot read property 'getLangs' of undefined
at MenuComponent_ng_container_0_Template (menu.component.html:14)
at executeTemplate (core.js:11937)
at refreshView (core.js:11784)
at refreshDynamicEmbeddedViews (core.js:13149)
at refreshView (core.js:11807)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
at refreshView (core.js:11836)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
defaultErrorLogger @ core.js:5882
handleError @ core.js:5935
(anonymous) @ core.js:42716
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41113
tick @ core.js:42713
(anonymous) @ core.js:42553
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41277
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41052
next @ core.js:42550
schedulerFn @ core.js:36880
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36842
checkStable @ core.js:41191
onLeave @ core.js:41352
onInvokeTask @ core.js:41261
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:481
invokeTask @ zone-evergreen.js:1596
globalZoneAwareCallback @ zone-evergreen.js:1633
load (async)
customScheduleGlobal @ zone-evergreen.js:1735
scheduleTask @ zone-evergreen.js:386
onScheduleTask @ zone-evergreen.js:273
scheduleTask @ zone-evergreen.js:379
scheduleTask @ zone-evergreen.js:211
scheduleEventTask @ zone-evergreen.js:237
(anonymous) @ zone-evergreen.js:1907
(anonymous) @ http.js:2603
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ finalize.js:11
subscribe @ Observable.js:23
error @ retry.js:29
_error @ Subscriber.js:75
error @ Subscriber.js:55
_trySubscribe @ Observable.js:50
subscribe @ Observable.js:28
call @ finalize.js:11
subscribe @ Observable.js:23
call @ retry.js:11
subscribe @ Observable.js:23
call @ catchError.js:16
subscribe @ Observable.js:23
subscribeToResult @ subscribeToResult.js:9
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
shareReplayOperation @ shareReplay.js:28
subscribe @ Observable.js:23
call @ take.js:22
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
shareReplayOperation @ shareReplay.js:28
subscribe @ Observable.js:23
call @ take.js:22
subscribe @ Observable.js:23
getTranslation @ ngx-translate-core.js:760
retrieveTranslations @ ngx-translate-core.js:739
setDefaultLang @ ngx-translate-core.js:670
AppComponent @ app.component.ts:14
AppComponent_Factory @ app.component.ts:18
getNodeInjectable @ core.js:5647
instantiateRootComponent @ core.js:12577
createRootComponent @ core.js:26377
create @ core.js:33914
bootstrap @ core.js:42668
(anonymous) @ core.js:42271
_moduleDoBootstrap @ core.js:42267
(anonymous) @ core.js:42222
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41277
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
(anonymous) @ zone-evergreen.js:851
invokeTask @ zone-evergreen.js:400
onInvokeTask @ core.js:41255
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
drainMicroTaskQueue @ zone-evergreen.js:570
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:553
scheduleTask @ zone-evergreen.js:389
scheduleTask @ zone-evergreen.js:211
scheduleMicroTask @ zone-evergreen.js:231
scheduleResolveOrReject @ zone-evergreen.js:841
then @ zone-evergreen.js:967
bootstrapModule @ core.js:42252
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.ts:13
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
Show 69 more frames
client:52 [WDS] Live Reloading enabled.
core.js:5882 ERROR TypeError: Cannot read property 'getLangs' of undefined
at MenuComponent_ng_container_0_Template (menu.component.html:14)
at executeTemplate (core.js:11937)
at refreshView (core.js:11784)
at refreshDynamicEmbeddedViews (core.js:13149)
at refreshView (core.js:11807)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
at refreshView (core.js:11836)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
defaultErrorLogger @ core.js:5882
handleError @ core.js:5935
(anonymous) @ core.js:42716
invoke @ zone-evergreen.js:365
run @ zone-evergreen.js:124
runOutsideAngular @ core.js:41113
tick @ core.js:42713
(anonymous) @ core.js:42553
invoke @ zone-evergreen.js:365
onInvoke @ core.js:41277
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:124
run @ core.js:41052
next @ core.js:42550
schedulerFn @ core.js:36880
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:36842
checkStable @ core.js:41191
onLeave @ core.js:41352
onInvokeTask @ core.js:41261
invokeTask @ zone-evergreen.js:399
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:481
invokeTask @ zone-evergreen.js:1596
globalZoneAwareCallback @ zone-evergreen.js:1633
core.js:5882 ERROR TypeError: Cannot read property 'getLangs' of undefined
at MenuComponent_ng_container_0_Template (menu.component.html:14)
at executeTemplate (core.js:11937)
at refreshView (core.js:11784)
at refreshDynamicEmbeddedViews (core.js:13149)
at refreshView (core.js:11807)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
at refreshView (core.js:11836)
at refreshComponent (core.js:13224)
at refreshChildComponents (core.js:11515)
Faça como o @wldomiciano postou:
export class MenuComponent {
constructor(public translate: TranslateService) {}
}
1 curtida