Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7658

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T05:54:09+00:00 2024-11-28T05:54:09+00:00

Preloading Data in Angular Universal

  • 60k

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

angularangularuniversaljavascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.