我在服务中具有以下功能:
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
}
如果我在服务中执行以下操作,则该功能可在app.module中访问,但不能使用this.router.url
:
export function saveURL() {
this.url = this.router.url;
}
答案 0 :(得分:2)
//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}