0

Using Angular router, when user navigates to a certain page of the SPA, I want to check if user is authenticated, by calling a service in ngOninit in order to display the sign-in or sign-out button as the case may be. But ngOninit doesn't fire, and only fires when I navigate away from the page in question. What could be the cause of that, am I missing lifecycle hooks lessons?

    export class HomeComponent implements OnInit {

     loggedIn? = false;

     constructor(private authservice: AuthenticationService) {}

     ngOnInit(): void {
      this.authservice.loadUserCredentials()
      .subscribe({
        next: res => {
          console.log('res ',res)
          this.loggedIn = res;
        }
      })
    }

    ```
    
Aviad P.
  • 32,036
  • 14
  • 103
  • 124
Uwem Uke
  • 19
  • 7
  • 1
    To check the user authentication you need to use auth Guards not a service in ngOnInit read more about it https://angular.io/api/router/CanActivate – Kamran Khatti Aug 04 '21 at 11:36
  • @KamranKhatti i do not want to guard any route at this point, i just want to call a service that checks if a user is authenticated, in order to show appropriate button, sign-in or sign-out. I have refactored to have the nav-bar wrap router-outlet instead of having nav-bar in each component, which came about by design. And the issue has been circumvented. But I'd still like to know why ngOninit fires only when i navigate away from the component. – Uwem Uke Aug 04 '21 at 13:52

1 Answers1

0
export class HomeComponent implements OnInit {

 loggedIn? = false;

 constructor(
private authservice: AuthenticationService,
    private router: Router,
) {}

 ngOnInit(): void {
  this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationEnd) {
        // Call your authenticate method
      }
}

In my ionic-angular app, I do it this way.

  • This looks like it might work in angular, though i'd refactored to circumvent that issue, will give it a try and get back to you. – Uwem Uke Aug 04 '21 at 14:50