简体   繁体   English

如何在app.module中的服务内部调用方法-Angular

[英]How to call a method inside of a service in app.module - Angular

I have a function in my service as follow: 我在服务中具有以下功能:

export class DualLogonService {
  url: string;
  constructor(private router: Router) {}

  saveURL(): void {
    this.url = this.router.url;
  }
}

App.module 应用模块

import { DualLogonService } from './ dual-logon/dual-logon.service';
...
export function saveUrl(dualLogonService: DualLogonService, router: Router) {
  console.log(router.url);TypeError: Cannot read property 'url' of undefined
  return dualLogonService.saveURL();//TypeError: Cannot read property 'saveURL' of undefined
}


{
  provide: APP_INITIALIZER,
  deps: [DualLogonService],
  useFactory: saveUrl,
  multi: true
}

If I do the following int the service, the function is accessible in the app.module, but I can't use the this.router.url : 如果我在服务中执行以下操作,则可以在app.module中访问该函数,但不能使用this.router.url

export function saveURL() {
   this.url = this.router.url;
}
  //This function should be above the @ngModel decorator
  export function callSaveUrl(dualLogonService: DualLogonService) {
       //Do what you need here
       return (): Promise<any> => { 
         return dualLogonService.saveUrl();
        }
  }


 DualLogonService,
 { provide: APP_INITIALIZER,useFactory: callSaveUrl, deps: [DualLogonService], multi: true}

Try something like this, its untested but I think this is what you are looking for 试试这样的东西,它未经测试,但我认为这是您正在寻找的

Change your code from 从更改您的代码

{
 provide: APP_INITIALIZER,
 deps: [DualLogonService],
 useFactory: saveUrl,
 multi: true
}

To this 对此

DualLogonService,
{ provide: APP_INITIALIZER,useFactory: callSaveUrl, deps: [DualLogonService], multi: true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 angular 中的 app.module 调用服务内的方法并使用 Imports 中的值 - How to call a method inside a service from app.module in angular and use the values in Imports Angular将HttpClient从app.module传递到另一个模块到服务 - Angular Pass HttpClient from app.module to another module to a service 如何在Angular 5中的app.module中读取appsettings文件? - How to read appsettings file in app.module in Angular 5? 如何将angular 2 app.module转换为es6 - how can I convert angular 2 app.module into es6 app.module 文件中缺少服务实例 - lack of service instance in app.module file 如何将app.module分成较小的文件? - How to separate app.module into smaller files? AngularCli将节点模块导入到角度app.module loadChildren - AngularCli Import node module to angular app.module loadChildren 在app.module和child.module中角导入FormsModule - Angular importing FormsModule in app.module vs child.module 如何使用服务在app.module上一次初始化变量,然后在其他组件中使用它? - How to initialize a variable once on the app.module using a service and use it later in other components? 如何在 Angular 的 app.module 中使用使用条件导出的 class? - How can I use a class that use conditional export in Angular's app.module?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM