• [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) {}
    }
  • 相关阅读:
    cf 427D Match & Catch 后缀数组
    cf 244c Checkposts 强连通分量
    NSPredicate的学习
    正则表达式
    NavigationBar &UINavigationItem& toolbar方法汇总
    区块股票数量
    吃什么
    selenium
    laravel5
    vim golang dev
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6843679.html
Copyright © 2020-2023  润新知