简体   繁体   English

可以再次调用 .forRoot 吗?

[英]Is it possible to call .forRoot again?

Usually when setting up an Angular Application, you set up all your modules on boot time, eg:通常在设置 Angular 应用程序时,您会在启动时设置所有模块,例如:

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?是否可以在应用程序中再次调用forRoot ,以便我可以分配一个新值?

The use-case is the following: I'm writing a module library, where you can set some properties with forRoot .用例如下:我正在编写一个模块库,您可以在其中使用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 ,但您可以将服务注入到组件或其他服务以及其上的所有方法或设置器或访问字段以更新其状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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