我有一个服务,该服务定义了要在多个组件之间共享的对象。我在APP_INITIALIZER期间调用的函数中设置该对象的值,乍一看似乎没问题,但是当我尝试从其他组件获取该对象时,它总是空的。
在我的data.service.ts中,我有这个:
// Object to be shared across components
private loggedUser = {};
setObject(user) {
this.loggedUser = user;
}
getObject() {
return this.loggedUser;
}
// Function that is correctly executed during the APP_INITIALIZER
Init() {
return new Promise<void>((resolve, reject) => {
this.getCurrentUser().subscribe((data: any) => {
// I receive an object with some properties here
this.setObject(data);
resolve();
});
});
}
然后在我的组件之一中,尝试使用以下方法获取该对象:
ngOnInit() {
var user = this.dataService.getObject();
console.log(user); // It's always empty
}
已编辑
:在我的app.module.ts中,我有一个工厂,该工厂将从Init()函数中接收承诺:
export function initializeApp1(appInitService: DataService) {
return (): Promise<any> => {
return appInitService.Init();
}
}
providers: [ DataService, { provide: APP_INITIALIZER, useFactory: initializeApp1, deps: [DataService], multi: true} ],
如您所见,我的目标是在APP_INITIALIZER期间设置一个对象,并在此之后在各个组件之间共享它。