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 }]
    })
  • 相关阅读:
    FZU-Problem 2150 Fire Game
    LeetCode120——Triangle
    Coder-Strike 2014
    AP INVOICES IMPORT API(NOT request)
    NYOJ-277-车牌号
    软件測试方法
    C++中字符数组和字符串string
    【机器学习算法-python实现】PCA 主成分分析、降维
    主题讲座:移动互联网时代的创业机会
    ubuntu环境eclipse配置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10299461.html
Copyright © 2011-2022 走看看