0

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

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
      }]
    };
  }
}
skink
  • 5,133
  • 6
  • 37
  • 58
bersling
  • 17,851
  • 9
  • 60
  • 74

1 Answers1

0

You can't call forRoot again, but you can inject the service to components or other services and all methods or setters on it or access fields to update its state.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I don't understand how I could do that. I don't have a service, I just have a component. There I inject `@Inject(SPINNER_CONSTANTS) private spinnerConstants: SpinnerConstants`. And those constants are linked in the providers. So how could I update it? Unless of course I add a service to the spinner which imports the initial constants, but then also lets me update the state and the component pull the state from the service as opposed to the constants. Is that what you meant? – bersling Oct 27 '17 at 05:16
  • Yes, make the constants fields of a service and inject this service instead. – Günter Zöchbauer Oct 27 '17 at 05:18