new method of ssr introduced in angular 17. how can i change status code of express response in angular components now? previously i changed the response like this:
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';
constructor(@Optional() @Inject(RESPONSE) private response: Response)
this.response.status(this.statusCode);
with this i could change the status code. for example if i met the not-found component i had to change the status code to 404 for SEO reasons.
The tokens aren't exported anymore by @angular/ssr
.
What the migration schematics currently does is that is creates them :
import { InjectionToken } from '@angular/core';
import { Request, Response } from 'express';
export const REQUEST = new InjectionToken<Request>('REQUEST');
export const RESPONSE = new InjectionToken<Response>('RESPONSE');
An you'll need to provide them : It could look something like that :
export function app(): express.Express {
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: distFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: RESPONSE, useValue: res },
{ provide: REQUEST, useValue: req })
],
}
Here is the PR that introduced that improvement for the schematics
Also as a note, ng serve
doesn't use server.ts
(it doesn't use express. The recommended approach to treat the tokens set in server.ts
as optional.