Express Server Providers for Angular 17's Server-Side Rendering

I attempted to share my request and response object with the Angular application by defining Providers in the "server.ts" file.
However, when injecting them into app.component, they always appear undefined regardless of whether I am in the server or client context.

Can anyone provide insight on how to resolve this issue? Unfortunately, there is a lack of information available.

I did not run the app in dev mode as Angular currently disregards server.ts in dev mode! - Instead, I built it and served the Express server.

The tokens are defined as follows:

export const REQUEST = new InjectionToken<Request>('REQUEST');
export const RESPONSE = new InjectionToken<Response>('RESPONSE');

My server setup is like this:

  // All regular routes use the Angular engine
  server.get('*', (req, res, next) => {
    console.log('HI HI HI hi');
    const { protocol, originalUrl, baseUrl, headers } = req;
    /*const transferState = inject(TransferState);
    transferState.set(makeStateKey<any>('t'), JSON.stringify('hi'));*/
    commonEngine
      .render({
        bootstrap,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: browserDistFolder,
        providers: [
          { provide: RESPONSE, useValue: res },
          { provide: REQUEST, useValue: req }
          ],
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

The Client injects the response object like so:

  constructor(@Optional() @Inject(RESPONSE) private response: Response) {
    super();
  }
  ngOnClientInit() {
    console.log('RESPONSE', this.response);
    console.log('I am on client', this.communicationService.getValue('data'), this.token);
  }

Unfortunately, no matter what attempts I make, my Response remains null.

I have searched via Google and reviewed the official documentation.

I am hopeful that the token will eventually return a value!

Answer №1

Currently, there is a recognized problem. Presently, the devServer does not utilize the server.ts configuration.

Answer №2

Turning off prerender fixed the issue completely

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capacitor-enabled Ionic Audio Recording

Finally completed my chat app, but I am looking to enhance the voice messaging feature to be more in line with Messenger rather than a standard file.wav format. Any suggestions or ideas would be greatly appreciated! https://i.stack.imgur.com/soXZC.png Cu ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

The Angular version update is experiencing issues within the Bash command prompt

https://i.stack.imgur.com/2ic0N.png I'm currently using version 6.0.8 of Angular, but when I try to add Angular/PWA to my project, I encounter an error. The command prompt shows my Angular CLI version as 6.0.8, however, in my bash command it displays ...

Is there any benefit to me verifying for Zone?

I have a custom function that allows me to execute another function within an Angular zone, regardless of whether it was called from outside of Angular. Check out my implementation: export class MyZones { public static maybe(zone: NgZone, callee: () ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

When incorporating React-query with Next.js and utilizing hydration configuration for server-side rendering, cached results are not utilized, leading to the need to perform another fetch request

While working on my nextjs app, I decided to implement react-query with SSR/SSG and went through several tutorials. I opted for the hydration configuration over the initialData approach as it seemed more efficient. Following the instructions in the react- ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

The element is implicitly imparted with an 'any' type due to the incapability of utilizing an expression of type 'number' to index the type '{}'. This error occurs in the context of VUEJS

I have encountered an issue that I have been struggling to resolve despite trying numerous solutions. The problem arises while working on a project using Vue. Here is how I have structured my data: data(){ return{ nodes: {}, edges:{}, ...

Tracking property changes in Angular can help developers easily identify modifications to specific

import { Component ,OnInit} from '@angular/core'; import { QuizService } from './quiz.service'; import { timer } from 'rxjs'; import { take, map } from 'rxjs/operators'; @Component({ selector: 'app-r ...

Unable to locate module src/ in Node.js TypeScript

I'm encountering issues with non-relative imports in my node.js / typescript application. Here is my tsconfig: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": ["dom", "es6", "es2017", "esnext.asynciterable"], "s ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

Are ngFormModel characteristics subject to change?

I've been facing challenges while working with ngFormModel and dynamic properties from classes. Despite my efforts, I'm unable to update the ngFormModel when changing variables to reflect new values. You can see an example of this issue in the fo ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

Live reload feature in Angular/Ionic app fails to update the app while running on Android Studio emulator

When running "ionic capacitor run android" in my Mac terminal, I can manually click the play button in Android Studio to view the application with its updated code changes. On the other hand, if I use "ionic capacitor run android -l" in my Mac terminal, t ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

Personalize the tooltip on ngx-charts heat map using custom tooltipTemplate

My attempt to personalize the tooltip of ngx-charts-heat-map led me to this code snippet: <ng-template #tooltipTemplate let-item="item"> <h1> {{getFlag(item.name)}} </h1> <h2>{{item.name}}: {{item.value}}</h2> </ ...

Troubles with Conditional Application of CSS Styles to a Twitter-Bootstrap Table

I am facing an issue with highlighting a row in a table when a barcode is entered. Despite following similar scenarios and checking my code, the CSS doesn't seem to be applied. Can anyone help me figure out what I'm missing or how I can fix this? ...

Issues with Angular 4 Rxjs subject subscription functionality

My application consists of a shared service named data.service.ts, which contains the following code: public pauseProjectTask$: Subject<any> = new Subject<any>(); pauseTaskProject(taskData, type){ this.pauseProjectTask$.next(taskData); ...