[英]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.