Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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$
    })
...
})
like image 447
mdziob Avatar asked Dec 29 '25 21:12

mdziob


1 Answers

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 {
         ...
    }
like image 69
mdziob Avatar answered Dec 31 '25 09:12

mdziob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!