I'm implementing a route guard (CanActivate interface) and I need to redirect to not found page under certain conditions. This can be achieved with the following sentence:
if (isNode){
let res : Response = Zone.current.get('res');
res.status(404).redirect('/not-found');
}else{
this.router.navigate(['not-found']);
}
This works, but raises an exception server side (Error: Can't set headers after they are sent), because angular2-universal still sends the rendered page, regardless of the redirection.
Is there any way to solve this properly?
Thanks in advance.
There is actually a solution for bypassing the error.
In server.ts
in the res.render
method add callback function and check for res.headersSent
boolean.
server.get('*', (req, res) => {
res.render('../public/index.html', {req, res},
(error, html) => {
if(error)
// error handle
if (!res.headersSent) {
res.send(html);
}
});
});
Obviously, send the html only if res.headersSent
is false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With