1

I'm trying out the new hydration feature present in Angular v16 and I can't seem to make it work with routing.

This is my setup:

app.config.ts:

const routes: Routes = [
  {
    path: 'hydration',
    component: HydrationComponent,
  }
];
export const appConfig: ApplicationConfig = {
  providers: [provideHttpClient(), provideClientHydration(), provideRouter(routes)]
};

hydration.component.html:

<p>There are {{ peopleInSpace().length }} people in space right now:</p>
<ul>
  <li *ngFor="let person of peopleInSpace()">
    {{ person.name }} ({{ person.craft }})
  </li>
</ul>

hydration.component.ts:

@Component({
  selector: 'app-hydration',
  standalone: true,
  templateUrl: './hydration.component.html',
  imports: [CommonModule],
})
export default class HydrationComponent implements OnInit {
  spaceService = inject(SpaceService);
  peopleInSpace = signal<Person[]>([]);

  ngOnInit(): void {
    this.spaceService
      .getPeople()
      .subscribe((result) => this.peopleInSpace.set(result));
  }
}

space.service.ts:

export interface Person {
  name: string;
  craft: string;
}

@Injectable({
      providedIn: 'root',
    })
    export class SpaceService {
      http = inject(HttpClient);
    
      getPeople(): Observable<Person[]> {
        console.log("Requesting data from Open Notify API");
        return this.http
          .get<any>('http://api.open-notify.org/astros.json')
          .pipe(map((res) => res.people));
      }
    }

If I just render the HydrationComponent directly in the AppComponent:

app.component.html:

<app-hydration/>

then hydration works and:

  • I don't see a request to the Open Notify API in the Dev tools
  • I see the <script id="ng-state"... tag WITH the cached API data from the server rendering

But if I use router-outlet instead

app.component.html:

<router-outlet/>

And I access /hydration, then

  • I see a request to the Open Notify API in the Dev tools
  • I see the <script id="ng-state"... tag WITHOUT the cached API data from the server rendering

meaning hydration didn't work properly. What I am missing here?

ecrb
  • 670
  • 4
  • 17

1 Answers1

0

Having had this same issue previously, I believe it may have been caused by a listed bug in Angular 16:

In a new angular 16 app I have found that SSR will not retrieve data in any component other than the app component.

This issue is listed as having been fixed in Angular version 16.0.5, and having run ng update to go to this version, the hydration problem no longer occurs for me.