Angular SSR - Load Data From Server Only

68 Views Asked by At

I'm trying to load data from the server only in Angular SSR (Universal). I have one idea from this post.

data-service.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export abstract class DataServiceService {
  abstract get(id: string): string
}

export class DataServiceServiceServer extends DataServiceService {
   get(id: string): string {
    return 'server-data-performed-with-secret-tokens';
   }
}

export class DataServiceServiceBrowser extends DataServiceService {
  get(id: string): string {
   return 'browser-data';
  }
}

app.config.server.ts

const serverConfig: ApplicationConfig = {
  providers: [
    provideServerRendering(),
    {
      provide: DataServiceService,
      useClass: DataServiceServiceServer
    }
  ]
};

app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClientHydration(),
    {
      provide: DataServiceService,
      useClass: DataServiceServiceBrowser,
    },
  ],
};

This will make sure the class can be used in both the server and the browser.

However, this returns different data on the client than the server. I'm thinking I would use the TransferState classes.

However, it looks like you don't need transferState with provideClientHydration.

When I try adding the transferState to this, it will not load on the client. Do I even need transferState, or is there a better way?

Repo

Open in StackBlitz

How can I use this to hydrate the client with the server value?

0

There are 0 best solutions below