You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
5 Hrs
22 Min
6 Seg

Implementando Angular Universal

14/23
Resources

How to configure Universal in Angular?

The Angular Universal configuration allows applications to run on the server using Node.js and Express to provide SSR (Server Side Rendering). This improves the load time and SEO of applications. Here's how to do it with simple commands and how to troubleshoot possible problems that may arise during the process.

Do I need official documentation?

Before performing any configuration, it is highly recommended to consult the official Angular documentation to fully understand the required steps and available features. This documentation will guide you through the process and make sure you do it correctly without forgetting crucial steps.

How to install Angular Universal?

  1. Install Angular Universal: Angular facilitates the configuration through a command that automates most of the process. This command takes into account Angular's structure and guidelines to generate a Node.js server in Express that will serve the application's files.

    ng add @nguniversal/express-engine

    When running this command, be sure to replace <project-name> with the actual name of your Angular project.

  2. Stop the development server: Before proceeding, make sure your development server is stopped to avoid conflicts.

  3. Execute the command in the terminal: Use the name of your project that is configured in Angular to execute the command:

    ng add @nguniversal/express-engine --clientProject <project-name> .

What modifications does Angular make?

When the command is executed, Angular performs several automatic modifications:

  • Generates a Node.js server in Express.
  • Configures the necessary changes to the angular.json file.
  • Creates tasks in the NPM scripts in order to build and serve the application.

In Visual Studio Code, you can easily visualize which files were created or modified after the command execution.

How to resolve common errors?

Sometimes, errors can occur when trying to run the project with Universal, such as failed unit tests or references to elements that only exist in the browser. If the build fails, it is most likely an issue with unit tests or client-side dependencies.

  1. Errors with unit tests: If unit tests fail, you can temporarily comment out the related code to continue development, although it is suggested to look for a thorough solution later.

  2. Browser references on the server: Errors such as direct references to window, document or browser-only elements need to be handled properly. Angular Universal provides classes to dynamically determine the execution environment and adapt the code accordingly.

How do we know when we are in a browser or server environment?

Angular provides classes that allow us to "intercept" different moments of code execution to adapt it according to the environment:

  • IS_PLATFORM_BROWSER: This function helps determine if the code is running in the browser.

    import { isPlatformBrowser } from '@angular/common';import { PLATFORM_ID } from '@angular/core';
    constructor(@Inject(PLATFORM_ID) private platformId: Object) { if (isPlatformBrowser(this.platformId)) { // Execute browser-specific logic }}
  • IS_PLATFORM_SERVER: This function lets you know if code is being executed on the server.

Learning and applying these techniques is crucial to manage robust applications that use Angular Universal effectively, ensuring correct SSR and smooth interaction between server and client.

Contributions 7

Questions 8

Sort by:

Want to see more contributions, questions and answers from the community?

El comando cambio en Angular9

ng add @nguniversal/express-engine

El comando para instalar Angular Universal es el siguiente:

ng add @nguniversal/express-engine

En el examen al seleccionar esa opción dice que está mal.

Hola, si alguno está siguiendo el tutorial con angular 8 le fallará cuando intentan compilarlo porque todavía no hay soporte de express-engine para angular 8.
Si quieren de igual manera hacerlo, deben desactivar el “enableIvy” en “angularCompilerOptions” en los archivos tsconfig.app.json y en tsconfig.json! saludos

Que dolor de cabeza es pasar una app a SSR. Lo importante es que eso vaya dentro de la planeación del proyecto para prevenir la mayor cantidad de errores posible. Ya después con el tiempo le agarras la onda a lo que debes de cuidar.

No se que hice o si tiene que ver con el hecho de ser la versión 9 pero no me da error lo del Swiper…

Vean en $ ng version que las versiones de (grupo 1):

  • @angular-devkit/architect
  • @angular-devkit/build-angular
  • @schematics/update

Sean iguales entre sí, así como de (grupo 2):

  • @angular-devkit/core
  • @angular-devkit/schematics
  • @angular/cdk
  • @angular/cli

En mi caso, el primer grupo marcaba 0.1102.14 y el segundo marcaba 11.2.14. Esto es importante recalcarlo porque si vienen de versiones muy viejas de Angular como yo, que en mi caso fui migrando desde ng7, muchos de estos paquetes no se actualizarán por igual y esto les puede dar dolores de cabeza al instalar Angular Universal por incompatibilidad del schematic y el devkit.

También recuerden modificar el comando que el profesor muestra para su versión de Angular. En mi caso utilicé:

$ ng add @nguniversal/[email protected] --clientProject

Por último, siempre revisen que la versión de Node sea compatible con la versión de Angular, además de tener NPM siempre en su última versión. Si usan NVM para portar diferentes versiones de Node en sus proyectos, es algo que deben de considerar por igual. En mi caso, tenía rato sin tocar Angular y tenía Node en versión superior a Angular, lo cual me producía errores.

hay que revisar la documentación con esto porque a la fecha, ha cambiado.