码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular] Tree shakable provider

时间:2019-01-21 17:11:47      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:oca   host   tab   factor   ace   rod   create   import   ever   

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 }]
})

 

[Angular] Tree shakable provider

标签:oca   host   tab   factor   ace   rod   create   import   ever   

原文地址:https://www.cnblogs.com/Answer1215/p/10299461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!