博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular] Tree shakable provider
阅读量:4355 次
发布时间:2019-06-07

本文共 1301 字,大约阅读时间需要 4 分钟。

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: 10};// Use providedIn & factory to make it as tree shakable provider.export const CONFIG_TOKEN = new InjectionToken
("CONFIG_TOKEN", { providedIn: "root", factory: () => APP_CONFIG});// Not tree shakable// export const CONFIG_TOKEN = new InjectionToken
("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 }]})

 

转载于:https://www.cnblogs.com/Answer1215/p/10299461.html

你可能感兴趣的文章
Python之set集合
查看>>
Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle
查看>>
Win7 下新版本Windows Virtual PC 安装SharePoint步骤详解
查看>>
SQLSERVER 升级版本的方法
查看>>
正则表达式基本语法详解
查看>>
BZOJ2132: 圈地计划
查看>>
PHP数据库连接mysql与mysqli的区别与用法
查看>>
char * 与char []探究理解
查看>>
QT窗体显示在屏幕中间位置
查看>>
emmet使用技巧
查看>>
RPC-Thrift(二)
查看>>
MSSQL for Linux 安装指南
查看>>
【Golang 接口自动化08】使用标准库httptest完成HTTP请求的Mock测试
查看>>
洛谷 P1036 选数
查看>>
女性社区TOP10
查看>>
BP神经网络算法推导及代码实现笔记zz
查看>>
前端必读:浏览器内部工作原理
查看>>
每天一个Linux命令(16)--which命令
查看>>
libevent文档学习(一)多线程接口和使用
查看>>
【补hackbar的坑】关于hackbar需要钱的补救措施
查看>>