Preloading Data in Angular Universal
Tags: javascript, angular, angularuniversal, webdev
Published: 2022-04-06 02:49:44

## 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](https://github.com/angular/angular/issues/53168).
### data.service.ts
Create a service with an injectable that can run on both the client and browser. Use an abstraction.
```ts
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>;
}
```
Now the server version:
```ts
// 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;
    }
}
```
And the browser version.
```ts
// 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;
    }
}
```
And a server load function. The `key` is for the state transfer in case you have other values you want to hydrate.
```ts
// Config
const key = 'test';

async function pageServerLoad() {
    return 'Random Number From Server: ' + Math.random();
}
```
### app.config.ts
Add the service just as in the original post below, however, you need to provide the class for the browser version.
```ts
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
    }
  ]
};
```
### app.config.server.ts
The server version gets merged with the browser class and overwrites the data service part with a browser provider.
```ts
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);
```
### app.component.ts
And you can inject it and use it just like any other service.
```ts
data = inject(DataService).value;
```
### app.component.html
```html
<p>{{ data }}</p>
```
**Demo**: [Vercel SSR](https://angular-vercel-ssr.vercel.app/)
**Repo**: [GitHub](https://github.com/jdgamble555/angular-vercel-ssr/tree/master)
___
## Original Post
___
After I wrote the code for my [last post](https://dev.to/jdgamble555/angular-universal-rest-api-endpoints-23fj), 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](https://dev.to/jdgamble555/forcing-angular-to-wait-on-your-async-function-2ck1). 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**

```typescript
providers: [{
    provide: APP_INITIALIZER,
    deps: [myService],
    useFactory: (rest: myService) => async () => await rest.getData(),
    multi: true
  }],
```
[Example File](https://github.com/jdgamble555/angular-endpoint-test/blob/master/src/app/app.module.ts)

**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.


```typescript
async getData(): Promise<void> {
  ...
  this.data = await this.fetchData();
}
```
Notice this function does not return anything.

[Example File](https://github.com/jdgamble555/angular-endpoint-test/blob/master/src/app/rest.service.ts)

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

```typescript
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;
  }
}
```

[Example File](https://github.com/jdgamble555/angular-endpoint-test/blob/master/src/app/app.component.ts)

The [full source code](https://github.com/jdgamble555/angular-endpoint-test) 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](https://angular-endpoint-test.vercel.app/). If you read my last post, you will notice the 'some data...' string is already in the DOM, and it now loads correctly.

J