Reputation: 3089
I have my ssr response service, with a redirect method among other:
import { Injectable, Inject } from '@angular/core';
import { Response } from 'express';
import { RESPONSE } from '@nguniversal/express-engine';
@Injectable()
export class SsrResponseService {
constructor(@Inject(RESPONSE) private response: Response) {}
redirect(url: string, code?: number) {
if (!!code) {
return this.response.redirect(code, url);
} else {
return this.response.redirect(url);
}
}
}
Then, in my component I need to redirect the user if some conditions aren't met:
this.responseService.redirect('/some-other-url', 301);
The redirect works fine, the user is redirected, but the server logs:
Unhandled Promise rejection: Can't set headers after they are sent. ;
Zone: <root> ; Task: Promise.then ; Value: Error: Can't set headers after they are sent.
Full stack trace: https://gist.github.com/MrCroft/c8a659567a3b248744b62a7cc04f061d
What can I do differently to avoid the error? Note that the decision can only be made from within the Angular application code.
Upvotes: 3
Views: 1969
Reputation: 2163
I had the same issue and found a workaround for it:
Instead of using this.response.redirect(url, code)
use:
this.response.status(code)
this.response.setHeader('Location', url);
Error vanishes
Upvotes: 6