[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) {}
}
原文地址:https://www.cnblogs.com/Answer1215/p/6843679.html