zoukankan      html  css  js  c++  java
  • [Angular] Tree shakable provider

    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<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 }]
    })
  • 相关阅读:
    博客园风格简单修饰(Do It Yourself)
    十大经典排序算法
    物流BOS
    算法设计
    牛客网刷题
    关于上网的问题
    Lucene&Solr
    SSM综合练习
    四十八:WAF绕过-权限控制之代码混淆及行为造轮子
    四十七:WAF绕过-漏洞发现之代理池指纹被动探针
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10299461.html
Copyright © 2011-2022 走看看