Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Angular SSR: ngAfterViewInit being called on server side, instead of client side

In my server-rendered Angular application using Angular 17, I have encountered a peculiar issue with the ngAfterViewInit lifecycle hook. The problem arises when calling an init function within ngAfterViewInit that depends on an API request requiring a valid access token, which is only available in the client's local storage.

Here's a simplified version of the code:

async init() {
  await this.loadData();
}

ngAfterViewInit(): void {
  this.init();
}

In this scenario, when the application is run via SSR, the page doesn't render, and the application keeps loading indefinitely. It seems that the init function is being executed on the server side, where the access token is not available, causing continuous retries without rendering any HTML.

However, if I introduce a delay using window.setTimeout, like the following:

ngAfterViewInit(): void {
  window.setTimeout(() => {
    this.init();
  }, 2000);
}

The page loads successfully because the init function is executed on the client side, where the access token is available.

Questions:

Why is ngAfterViewInit being called on the server side in the first case, contrary to its intended behavior of being called on the client side after the view is initialized?

Note that, I am not using angular universal. Instead, I am using the built in SSR of angular 17

Upvotes: 3

Views: 957

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55669

Angular lifecycle hooks are run of both the server side and the client side.

You're probably looking for the afterNextRender() hooks which is only run on the client side :

ngAfterViewInit(): void {
   afterNextRender(() => this.init(););
}

Upvotes: 5

Related Questions