Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Passing data or events from child to parent with router-outlet

Tags:

angular

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.

like image 449
pupil Avatar asked Feb 21 '18 08:02

pupil


People also ask

Can we pass data in router outlet in Angular?

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/…

Can we pass data from child to parent in Angular?

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.

How do you pass data from child component to parent component in Angular?

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.


1 Answers

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.

like image 128
Aakriti.G Avatar answered Sep 25 '22 19:09

Aakriti.G