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



我的服务中有一个函数如下:

export class DualLogonService {
  url: string;
  constructor(private router: Router) {}
  saveURL(): void {
    this.url = this.router.url;
  }
}

应用模块

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
}

如果我在服务中执行以下操作,则可以在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}

尝试这样的东西,它未经测试,但我认为这就是你要找的

将代码从

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

对此

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

最新更新