简体   繁体   中英

Pass variable to module using forRoot

I've developed a library with shared components in Angular and I want to pass configuration there.

Everything is basically the same as in: Pass config data using forRoot

Problem is, that I need to pass user to this module, which is fetched on start of application and saved in Redux state.

Is it possible to pass observable with user using forRoot while importing module? Maybe it's possible to pass something to this module 'later' with some lazy loading?

@select() private user$: Observable<User>

@NgModule({
  imports: [
    LibModule.forRoot({
      user: user$
    })
...
})

I've made it another way - by injecting my implementation of abstract service for getting settings. Code below:

Lib module declaration:

export interface LibSettings {
  user: User;
  url: string;
}

export abstract class AbstractLibSettingsService {
  abstract getSettings(): LibSettings;
}

@NgModule({
  declarations: [...],
  imports: [...],
  exports: [...]
})
export class LibModule {

  static forRoot(implementationProvider: Provider): ModuleWithProviders {
    return {
      ngModule: LibModule,
      providers: [
        implementationProvider
      ]
    }
  }
}

Lib service, where I needed the user:

constructor(private settingsService: AbstractGlassLibSettingsService) {
}

In application that uses the lib, module declaration with import:

export const LIB_SETTINGS_PROVIDER: ClassProvider = {
    provide: AbstractLibSettingsService,
    useClass: LibSettingsService
};

@NgModule({
    imports: [...
        LibModule.forRoot(LIB_SETTINGS_PROVIDER)
    ],
...
})

Finally, the implementation of the service in application:

@Injectable()
export class LibSettingsService extends AbstractLibSettingsService {

    @select() private user$: Observable<User>;
    private user: User;

    constructor() {
        super();
        this.user$.subscribe(user => this.user = user);
    }

    public getSettings(): GlassLibSettings {
         ...
    }

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