Angular service doesn't work within other service

送分小仙女□ 提交于 2019-12-11 17:34:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!