pupil
pupil

Reputation: 254

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

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.

Upvotes: 6

Views: 10541

Answers (2)

Prasanth S
Prasanth S

Reputation: 535

am just expanding 'Hrishikesh Kale' answer a bit, from your view, you are storing user credentials in localstorage.

just get that stored data in service

credentials(){
    const usercredential = localStorage.getItem('usercredential')
    if(usercredential === "undefined"){
      return false
    }
    else {
      return true
    }
  }

and in your html

<a *ngIf="service.loggedIn() && service.credentials()">Admin</a>

Upvotes: 1

Aakriti.G
Aakriti.G

Reputation: 686

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.

Upvotes: 17

Related Questions