首页 > 解决方案 > 如何从 Angular 的模块文件中调用在服务内部编写的函数?

问题描述

我需要从app.modulesharedService调用一个函数。通常我们通过添加依赖注入并在类中调用它来做到这一点。但我这里的情况不同。当 ngxs 商店作为提供者添加到 app.module 时,我想从服务文件中设置一个。除了从sharedService调用函数getAcceptedValue()来获得我想要的值之外,我没有任何其他选择。我想在模块的提供者部分调用performStoreOperations 。

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);
  }
}

有人可以帮忙吗?

标签: angulardependency-injectionangular9angular-modulengxs

解决方案


你可以这样做。

来自模块 A 的 SharedService


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

模块 A

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

一些.component.ts

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

推荐阅读