[Angular] Tree shakable provider
2024-08-28 23:12:47
When we create a Service, Angluar CLI will helps us to add:
@#Injectable({
providedIn: 'root'
})
It only create a instance in root dependency tree. If there is no reference to use this provider, Angular will remove it from our production code.
But the service we created are Class based service, what if we want to create some Object and inject this Object to our application and we want to make it tre shakable as well.
We can do as following:
import { InjectionToken } from "@angular/core";
export interface AppConfig {
apiUrl: string;
courseCacheSize: number;
} export const APP_CONFIG: AppConfig = {
apiUrl: "http://localhost:9000",
courseCacheSize:
}; // Use providedIn & factory to make it as tree shakable provider.
export const CONFIG_TOKEN = new InjectionToken<AppConfig>("CONFIG_TOKEN", {
providedIn: "root",
factory: () => APP_CONFIG
}); // Not tree shakable
// export const CONFIG_TOKEN = new InjectionToken<AppConfig>("CONFIG_TOKEN");
Whereever you use the provider, you need to remove it:
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
// Remove it when need to use tree shakable provider
providers: [{ provide: CONFIG_TOKEN, useValue: APP_CONFIG }]
})
最新文章
- JavaScript Object对象
- JS原型链
- Hibernate的三种状态
- choco命令
- HDU3530 子序列
- xcode 开发ios兼容性问题的上下黑边 和 coco2d-x 游戏分辨率适配 ResolutionPolicy::FIXED_WIDTH 都会引起上下黑边问题!!!
- [BZOJ 3888] [Usaco2015 Jan] Stampede 【线段树】
- 模板-->;中国剩余定理[互质版本]
- 马士兵 Servlet &; JSP(1) Servlet (源代码)
- JavaScript 常用小代码
- MYSQL 巧用count,sum进行统计数据
- HDU - 1116 Play on Words(欧拉图)
- S3C2440之IIC裸机驱动
- Storm官方文档翻译之设置开发环境
- Django 模型和数据库 总结
- python 闯关之路三(面向对象与网络编程)
- Linux kernel的中断子系统之(七):GIC代码分析
- self_vs_default_definee_vs_receiver
- IIS 发布ASP.NET MVC 4.0 错误500.21解决办法
- python 进程锁 生产者消费者模型 队列 (进程其他方法,守护进程,数据共享,进程隔离验证)