angular - 如何将依赖项注入Angular 8中的类
问题描述
我想在我的类的静态类中使用 ngx translate。我怎样才能做到这一点?如何在单例类中进行依赖注入?
import { Injectable } from "@angular/core";
@Injectable()
export class MyService {
static instance: MyService;
static getInstance() {
if (MyService.instance) {
return MyService.instance;
}
MyService.instance = new MyService();
return MyService.instance;
}
constructor() {
if (!MyService.instance) {
MyService.instance = this;
}
return MyService.instance;
}
}
解决方案
只需使用单例服务。Angular 已经涵盖了你,因为 Singleton 是由 DI 容器在内部管理的。该实例只会创建一次,注入MyService
另一个组件将等同于您的MyService.getInstance()
.
您只需providedIn
将服务范围设置为"root"
:
@Injectable({
providedIn: 'root',
})
export class MyService {
// ...
}
推荐阅读
- eclipse - Eclipse中如何查看Java类的源代码而不用ctrl+click?
- ruby - 如何在 Ruby 中实现自定义变异方法?
- javascript - 如何根据 colspan 属性的值删除 HTML 表 td?
- symfony4 - 使用私有方法在 Symfony 中测试服务
- python - 在 NLTK Brown Corpus 上训练 Gensim word2vec 时遇到问题
- c++ - 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出?
- python - 如何配置 uWSGI 以便使用 pdb 进行调试(--honour-stdin 配置问题)
- rest - 我应该使用接受 http 标头还是更明确的 rest api 资源来定义客户端请求的数据格式?
- android - 可以在内部测试轨道上测试 Google Play 游戏服务吗?
- python - 使用 beautifulsoup 隐藏元素进行网页抓取