1

I have two components navbarcomponent and logincomponent.

  <app-navbar></app-navbar>
  <app-login></app-login>

navbarcomponent get executed before the logincomponent. In my logincomponent while the user login i set the the user informations in local storage. and i'm calling it in ngoninit of my navbarcomponent.

ngOnInit() {
this.user = localStorage.getItem("user");
}

But the user variable is always null . because it get executed before the logincomponent instantiate it.

Is there a way to get the value after the method in login get executed ?

patron
  • 59
  • 3
  • 10

2 Answers2

1

You need to create a service for sharing data between 2 components.

export class CheckLoginService {
    public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

    callLoadData(value: boolean) {
        this.status.next(value);
    }
}

NavbarComponent :

export class NavbarComponent implements OnInit {

  constructor(private checkLoginService: CheckLoginService) { }
  isLoggedIn: boolean = false
  sessionFirstName: string


  ngOnInit() {
    this.checkLogin()
    this.checkLoginService.status.subscribe((val: boolean) => {
      if (val == true) {
        this.sessionFirstName = localStorage.getItem('sessionFirstName');
      }
    });
  }

}

LoginComponent

login(user:any) {
    localStorage.setItem('sessionFirstName', user.userFirstName)
    this.checkLoginService.callLoadData(true);
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

You can also make use of EventEmitter and Input to update the value between two child components.

Login.Component.ts

@Output() updateUserNameEmitter = new EventEmitter();

login(){
  this.updateUserNameEmitter.emit(localStorage.getItem("user");)
}

App.component.html

<app-login (updateUserNameEmitter)="updateUserName($event)"></app-login>
<app-navbar [userName]="userName"></app-navbar>

App.Component.ts

public userName: string;

updateUserName(userName){
 this.userName = userName;
}
Suhas Parameshwara
  • 1,344
  • 7
  • 15
  • 1
    This is a simpler way to share data if both the components are child of same parent component. However for login case, its better to create a service as logout can occur from other services as well such as from httpinterceptor service on token expiration, For updating navbar at that time service is needed – Adrita Sharma Nov 07 '19 at 09:40
  • 1
    @AdritaSharma yea agree. – Suhas Parameshwara Nov 07 '19 at 09:42