3

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$
    })
...
})
mdziob
  • 1,116
  • 13
  • 26

1 Answers1

1

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 {
         ...
    }
mdziob
  • 1,116
  • 13
  • 26
  • Where you find the documentation for solution? I'm intersting in that i can return `imports` in the `static forRoot` function – jgu7man Mar 30 '21 at 14:17
  • I'm afraid that I don't undestand your question... could you re-phrase it? To be honest, I think I was just experimenting and came up to this solution. – mdziob Mar 31 '21 at 18:49
  • After last afternoon I've understand the strategy "forRoot" and now I know that had no sense. I'm sorry jeje – jgu7man Mar 31 '21 at 20:02