问题描述
我有一个带路由登录,主页等路由的父级AppComponent.当用户使用凭据登录时,我将用户凭据保存在Sessionstorage中.登录成功后,我想在AppComponent.html的标头中显示部分数据,因此我必须从seesionstorage中获取getItems.如何触发事件以从LoginComponent通知AppComponent?我正在使用路由器插座,所以无法使用EventEmitter.我可以使用BehaviourSubject,但是AppComponent中没有有效的方法可以调用.请提出建议.
I have parent AppComponent with routes login, home etc. When user logs in with creds, I'm saving the user creds in Sessionstorage. When the login is successful I want to display some part of the data in header of AppComponent.html, so I have to getItems from seesionstorage. How do I trigger the event to notify AppComponent from LoginComponent? I'm using router-outlet so I cannot use EventEmitter. I can use BehaviourSubject but there is no valid method in AppComponent to call.Please suggest.
推荐答案
为此使用通讯服务:
CommunicationService.ts
CommunicationService.ts
@Injectable()
export class CommunicationService {
constructor() { }
private emitChangeSource = new Subject<any>();
changeEmitted$ = this.emitChangeSource.asObservable();
emitChange() {
this.emitChangeSource.next();
}
}
login.ts:
constructor(
private communicationService: CommunicationService
) {
}
login(){
this.communicationService.emitChange()
}
AppComponent.ts:
AppComponent.ts:
constructor(
private communicationService: CommunicationService,
) {
communicationService.changeEmitted$.subscribe(data => {
// here fetch data from the session storage
})
}
希望这会有所帮助.
这篇关于角度:通过路由器出口将数据或事件从子级传递到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!