DEV Community

Cover image for Preloading Data in Angular Universal
Jonathan Gamble
Jonathan Gamble

Posted on • Updated on

Preloading Data in Angular Universal

Update 3/2/24 - Angular 17 with Server Hydration

Now that Hydration has changed, you can update this method a bit to work with an abstraction. Got half of this working from Angular Team Post.

data.service.ts

Create a service with an injectable that can run on both the client and browser. Use an abstraction.

import { 
  Injectable, 
  TransferState, 
  inject, 
  makeStateKey 
} from '@angular/core';

type PageLoad = Awaited<ReturnType<typeof pageServerLoad>>;

// Abstract
@Injectable()
export abstract class DataService {
    abstract value: PageLoad | null;
    abstract load(): Promise<void>;
}
Enter fullscreen mode Exit fullscreen mode

Now the server version:

// Server
@Injectable()
export class DataServiceServer extends DataService {
    state = inject(TransferState);
    value: PageLoad | null = null;
    async load() {
        const data = await pageServerLoad();
        this.state.set(makeStateKey<PageLoad>(key), data);
        this.value = data;
    }
}
Enter fullscreen mode Exit fullscreen mode

And the browser version.

// Browser
@Injectable()
export class DataServiceBrowser extends DataService {
    state = inject(TransferState);
    value: PageLoad | null = null;
    async load() {
        const data = this.state.get(makeStateKey<PageLoad>(key), null);
        this.value = data;
    }
}
Enter fullscreen mode Exit fullscreen mode

And a server load function. The key is for the state transfer in case you have other values you want to hydrate.

// Config
const key = 'test';

async function pageServerLoad() {
    return 'Random Number From Server: ' + Math.random();
}
Enter fullscreen mode Exit fullscreen mode

app.config.ts

Add the service just as in the original post below, however, you need to provide the class for the browser version.

import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { DataService, DataServiceBrowser } from './data.service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClientHydration(),
    {
      provide: DataService,
      useClass: DataServiceBrowser
    },
    {
      provide: APP_INITIALIZER,
      deps: [DataService],
      useFactory: (ds: DataService) => async () => await ds.load(),
      multi: true
    }
  ]
};
Enter fullscreen mode Exit fullscreen mode

app.config.server.ts

The server version gets merged with the browser class and overwrites the data service part with a browser provider.

import { 
  mergeApplicationConfig, 
  ApplicationConfig 
} from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
import { DataService, DataServiceServer } from './data.service';

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

export const config = mergeApplicationConfig(appConfig, serverConfig);
Enter fullscreen mode Exit fullscreen mode

app.component.ts

And you can inject it and use it just like any other service.

data = inject(DataService).value;
Enter fullscreen mode Exit fullscreen mode

app.component.html

<p>{{ data }}</p>
Enter fullscreen mode Exit fullscreen mode

Demo: Vercel SSR
Repo: GitHub


Original Post


After I wrote the code for my last post, I realized I had a fundamental misunderstanding about how Angular Universal can pre-fetch data.

Original Work Around

In certain circumstances, you can use ZoneJS's scheduleMacroTask in order to run code outside of your component. You can't preload something in a constructor, because it is a constructor that returns a new object. The ngOnInit may work, depending on your circumstances.

No, it wasn't until I started learning other frameworks that Angular Universal Providers started to make sense. If you go back and read my past articles, you can start to see this evolution.

In order to prefetch your data correctly, you must load it outside of your component first. You can't always use the ZoneJS hack, because it could cause circular functions that rely on each other.

Other Frameworks

The biggest thing I hate about React is how it handles state. Once you start digging into NextJS, NuxtJS, and SvelteKit, you realize the data is always preloaded from the function / class, and then the data is passed to that class.

Angular Universal

This is how Angular Universal is meant to handle your data. If you Google the many stackoverflow articles, you will see this process extremely over complicated.

Basically you're going to load your data in a in your app.module.ts from your service using APP_INITIALIZER. The service itself does not return any data, but keeps the data in state.

app.module.ts

providers: [{
    provide: APP_INITIALIZER,
    deps: [myService],
    useFactory: (rest: myService) => async () => await rest.getData(),
    multi: true
  }],
Enter fullscreen mode Exit fullscreen mode

Example File

myService.ts

Here you just fetch the data, and save it to a variable like this.data. When you pass this instance of the service as your providers to the new component, it will be ready to be loaded in the this.data variable.

async getData(): Promise<void> {
  ...
  this.data = await this.fetchData();
}
Enter fullscreen mode Exit fullscreen mode

Notice this function does not return anything.

Example File

app.component.ts
Here you literally just get the data from your service this.data, and do with it as you please. Incredibly simple.

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

import { RestService } from './rest.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  title = 'angular-test';
  data: string;

  constructor(private rest: RestService) {
    this.data = this.rest.data;
  }
}
Enter fullscreen mode Exit fullscreen mode

Example File

The full source code was used for my last post, so you can see it fully in action with proper state transfer, a rest api, and deployed to Vercel.

See it in action. If you read my last post, you will notice the 'some data...' string is already in the DOM, and it now loads correctly.

J

Latest comments (0)