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.
It is possible to transfer data through router-outlet directive. We can use "activate" event for this. For more details read my article See also angular.io/guide/…
The Angular documentation says "The @Output() decorator in a child component or directive lets data flow from the child to the parent." This is exactly what we want.
The @Output() decorator in a child component or directive lets data flow from the child to the parent. @Output() marks a property in a child component as a doorway through which data can travel from the child to the parent.
Use communication service for this:
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:
constructor(
private communicationService: CommunicationService,
) {
communicationService.changeEmitted$.subscribe(data => {
// here fetch data from the session storage
})
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With