Angular 服务在其他服务中不起作用 [英] Angular service doesn't work within other service

查看:29
本文介绍了Angular 服务在其他服务中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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.

推荐答案

你是否在 SharedModule 中的导出数组中添加了 TranslateModule?

Did you add TranslateModule to exports array in SharedModule?

您的自定义语言服务是否在 root 中提供?

Is your custom LangService provided in root?

这是一个例子:

1- 您的定制服务:

@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 服务在其他服务中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆