zoukankan      html  css  js  c++  java
  • [Angular] Configurable NgModules

    You probably have seen 'foorRoot()' method a lot inside Angular application.

    Creating a configurable NgModule allows us do the configuration for each serivce.

    // service module
    
    import { NgModule, ModuleWithProviders, Provider } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { HttpModule } from '@angular/http';
    
    import { FOOD_STORE_CONFIG, FoodStoreConfig } from './config';
    import { FoodStoreService } from './food-store.service';
    
    export const FOOD_PROVIDERS: Provider[] = [
      FoodStoreService
    ];
    
    @NgModule({
      imports: [
        CommonModule,
        HttpModule
      ]
    })
    export class FoodStoreModule {
      static forRoot(config: FoodStoreConfig): ModuleWithProviders {
        return {
          ngModule: FoodStoreModule,
          providers: [
            ...FOOD_PROVIDERS,
            {
              provide: FOOD_STORE_CONFIG,
              useValue: config
            }
          ]
        };
      }
    }
    import { InjectionToken } from '@angular/core';
    
    export interface FoodStoreConfig {
      storeId: number,
      storeToken: string
    }
    
    export const FOOD_STORE_CONFIG = new InjectionToken<FoodStoreConfig>('FOOD_STORE_CONFIG');

    Then in the app.module.ts:

      imports: [
        BrowserModule,
        HttpModule,
        FoodStoreModule.forRoot({
          storeId: 10292,
          storeToken: 'eca938c99a0e9ff91029dc'
        })
      ],

    Now the 'FoodStoreService' can be used any where inside our application:

    // app.component.ts
    
    @Component({
      selector: 'app-root',
      template: `
        <div>
          Food Store ({{ (store | async)?.name }})
        </div>
      `
    })
    export class AppComponent {
      store = this.foodService.getStore();
      constructor(private foodService: FoodStoreService) {}
    }
  • 相关阅读:
    【BZOJ2525】[Poi2011]Dynamite 二分+树形DP
    【BZOJ2560】串珠子 状压DP+容斥
    【BZOJ2726】[SDOI2012]任务安排 斜率优化+cdq分治
    [NOIP2017]宝藏 状压DP
    [NOIP2017]逛公园 最短路+拓扑排序+DP
    [NOIP2017]列队 离线+SBT
    【CF628D】Magic Numbers 数位DP
    【BZOJ2791】[Poi2012]Rendezvous 倍增
    sql 通过游标 拆分xml结构
    sql字符转换函数大全
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6843679.html
Copyright © 2011-2022 走看看