问题
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 );
}
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 );
}
Now I simply inject LangService to my component, but the translation doesn't work. Any idea?
Note: I imported TranslateModule into a SharedModule, and import that SharedModule in my other lazy loaded modules.
回答1:
Did you add TranslateModule to exports array in SharedModule?
Is your custom LangService provided in root?
Here is an example:
1- Your custom service:
@Injectable({
providedIn: 'root'
})
export class CustomTranslateService {
constructor(private translate: TranslateService) {}
}
2- Add TranslateModule to exports array in your SharedModule.
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...
}
}
来源:https://stackoverflow.com/questions/56030377/angular-service-doesnt-work-within-other-service