skip to Main Content

Create a project with angular v17 and SSR

In my app.component.ts i retrieve list of products from my api.

constructor(    
    private product: ProductService
  ) {
    this.product.getProductos().subscribe(p => {
      this.productos = p;      
    });
  }

In my app.component.html i display the list of products

  <li *ngFor="let producto of productos">
          {{ producto.nombre }} - {{ producto.precio  }}
   </li>

When I visit the url, in the first network request where the server-side rendered html document is loaded, the products obtained from the api are not displayed.

I have tried forcing the call server side

 constructor(
    private product: ProductService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    if (isPlatformServer(this.platformId)) {
      this.product.getProductos().subscribe(p => {
        this.productos = p;
      });
    }

My app.config

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideClientHydration(
      withNoHttpTransferCache()     
    ),
    provideHttpClient(
      withFetch()
    )
  ]
};

I need to render that data on the server side to optimize the website’s SEO.

If anyone has run into this problem of trying to render dynamic data server-side and solved it, I would appreciate a response.

2

Answers


  1. You have configured client hydration withNoHttpTransferCache. According to the docs, this is what it does:

    Disables HTTP transfer cache.
    Effectively causes HTTP requests to be performed twice:
    once on the server and other one on the browser.

    Apparently, this is not what you want. So simply remove withNoHttpTransferCache(), and the request won’t be done in the browser.

    Or, if you want to configure the caching, use withHttpTransferCacheOptions.

    Login or Signup to reply.
  2. I had the same problem here. The reason was there was an error on the server side build (in my case with window object which is not available on the server) and for that reason the api data was not injected into html. Strange, but you should look into that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search