简体   繁体   中英

Is it possible to call .forRoot again?

Usually when setting up an Angular Application, you set up all your modules on boot time, eg:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import {SpinnerModule} from './spinner/spinner.module';
import { OverrideOneComponent } from './override-one/override-one.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    OverrideOneComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    SpinnerModule.forRoot({
      animation: 'spin 1.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite',
      smallSize: 16,
      mediumSize: 40,
      largeSize: 60
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

So then the properties are fixed throughout the lifetime of the application. Is it possible to call forRoot again mid-application, so I could assign a new value?

The use-case is the following: I'm writing a module library, where you can set some properties with forRoot . The end user usually sets them at boot time. But to showcase different settings, I'd like to make a demo page, where I can dynamically change the properties of the module. So I'd need a way to "reboot" the module... Is that possible?

Edit: The module in this case would look like:

import {NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import { SpinnerComponent } from './spinner/spinner.component';
import {SPINNER_CONSTANTS} from './constants';
import {SpinnerConstants} from './spinner-constants.interface';

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [
    SpinnerComponent
  ],
  declarations: [
    SpinnerComponent
  ]
})
export class SpinnerModule {
  static forRoot(spinnerConstants: SpinnerConstants) {
    return {
      ngModule: SpinnerModule,
      providers: [{
        provide: SPINNER_CONSTANTS,
        useValue: spinnerConstants
      }]
    };
  }
}

您不能再次调用forRoot ,但您可以将服务注入到组件或其他服务以及其上的所有方法或设置器或访问字段以更新其状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM