How can i call a function written inside service from a module file in angular?

Viewed 361

I need to call a function from sharedService from app.module . Usually we do it by adding dependency injection and calling it inside the class. But my case here is different. I want to set a value from service file when the ngxs store is added as a provider in app.module. I dont have any other option other than calling the function getAcceptedValue() from sharedService to get my desired value. I want to call performStoreOperations in the providers part of module.

import {SharedService} from './shared.service';

@NgModule({
  imports: [
    NgxsModule.forFeature([
      AuthState,
    ]),
    NgxsResetPluginModule.forRoot(),
    SharedModule,
    NgxsReduxDevtoolsPluginModule.forRoot(),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: NGXS_PLUGINS,
      useValue: performStoreOperations, // How to call performStoreOperations function here ???????
      multi: true,
    },
  ],

})
export class AppModule {
  constructor(private shared:SharedService){}

  performStoreOperations(state, action, next) {
  {
    let acceptedValue = this.shared.getAcceptedValue(); 
    localStorage.setItem('test',acceptedValue);
    return next(state, action);
  }
}

Can anyone please help?

1 Answers

You can do it like this.

SharedService from Module A


    scroll(el: HTMLElement, behaviour: any = "smooth", block: any = "start", inline: any = "nearest") {
        el.scrollIntoView({ behavior: behaviour, block: block, inline: inline })
      }

Module A

    @NgModule({
      declarations: [],
      imports: [//some components],
      exports: [//some components],
      providers: [
        SharedService,
      ]
    })
    export class SharedModule { }

some.component.ts

    import {sharedService} from 'your/path/t
    constructor(private sharedService: SharedService){}
    //do something with this.sharedService.scroll(param1,...........etc)
Related