问题描述
我正在使用ngx-translate
库进行翻译.在我的组件中(延迟加载的路由),当我设置以下内容时,它可以正常工作:
I'm using ngx-translate
library for translations. In my components (lazy loaded routes) When I set the following, it works fine:
constructor( public translate:TranslateService ) {
this.translate.setDefaultLang( this.langService.lang );
this.translate.use( this.langService.lang );
}
我有自己的 LangService ,用于保存用户选择的语言.我将其设置为lang
属性,并在其中使用TranslateService:
I have my own LangService just to save user's selected language. I set it to lang
property and use TranslateService there:
lang:string = "fa";
constructor(public translate: TranslateService) {
// this works
console.log(this.lang);
// this doesn't work
this.translate.setDefaultLang( this.lang );
this.translate.use( this.lang );
}
现在,我只是将LangService注入到我的组件中,但是翻译不起作用.有什么主意吗?
Now I simply inject LangService to my component, but the translation doesn't work. Any idea?
注意:我将TranslateModule导入了SharedModule,并在其他延迟加载的模块中导入了该SharedModule.
Note: I imported TranslateModule into a SharedModule, and import that SharedModule in my other lazy loaded modules.
推荐答案
您是否将TranslateModule添加到SharedModule中的导出数组?
Did you add TranslateModule to exports array in SharedModule?
您的自定义LangService是否在根目录中提供?
Is your custom LangService provided in root?
这里是一个例子:
1-您的自定义服务:
1- Your custom service:
@Injectable({
providedIn: 'root'
})
export class CustomTranslateService {
constructor(private translate: TranslateService) {}
}
2-将TranslateModule添加到SharedModule中的导出数组.
2- Add TranslateModule to exports array in your SharedModule.
3-将您的自定义服务注入您的组件中:
3- Inject your custom service in your components:
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class FooterComponent implements OnInit {
constructor(private translate: CustomTranslateService) {
}
ngOnInit(): void {
// Use it here...
}
}
这篇关于Angular服务在其他服务中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!