app.component ngOnInit loads after component ngOnInit

Discussão em 'Angular' iniciado por Brian, Abril 3, 2025.

  1. Brian

    Brian Guest

    I am using a signal to store the logged in user. When loading a page I want to load the logged in user from a token. This is done in ngOnInit in app.component:

    ngOnInit(): void {
    // Check if `the user is logged in
    const token = localStorage.getItem('token');
    if (token) {
    this.userService.getUser().subscribe((user) => {
    if (user) {
    this.authService.currentUserSig.set(user)
    }
    });
    } else {
    // User is not logged in, redirect to login page or perform other actions
    console.log('User is not logged in');
    }


    }

    Within my component I want to check if a user is authenticated before loading the component, otherwise redirect to the login page:

    ngOnInit(): void {
    if (this.authService.currentUserSig()) {
    this.loadStudents()
    }
    else {
    this.router.navigateByUrl('/login');
    }


    }

    The problem is the signal is undefined when the ngOnInit is loaded in the component because the asynchronous call in the app.component has not set the value yet. How can I make sure the logic in ngOnInit in the app.component finished loading before the component attempts to load?

    Continue reading...

Compartilhe esta Página