In our preceding example, we passed a dynamic parameter from a route to a component. However, because this parameter can be anything that is provided as the URI segment after /posts, we will need to handle the error case for what happens when this value is invalid. The easiest thing to do here is to check whether the value is indeed a valid number, and if it is not, redirect the user to the 404 page we created.
Programmatic page redirection in Angular
How to do it...
Let's add a 404 page to our application for when a user attempts to access an invalid route:
- We can redirect a user to our 404 page using the Angular router's navigateByUrl method:
...
export class PostComponent implements OnInit {
postId = null;
constructor(private route:ActivatedRoute, private router:Router) {
route.params.subscribe(
params =>{
this.postId = parseInt(params['id']);
if (isNaN(this.postId)) {
this.router.navigateByUrl("/404")
}
}
);
}
}
- To prevent the browser's URL from showing the /404 route name, we will provide the skipLocationChange flag:
...
if (isNaN(this.postId)) {
this.router.navigateByUrl("/404", { skipLocationChange: true })
}
...
- Now when we land on an invalid route, we will see the 404 page content without updating the browser's URL.
How it works...
Since /404 isn't a defined route in our application, it gets picked up by our wildcard path route configuration. Additionally, it exhibits an unintended behavior; the URL in the browser points at /404. Even worse, if the user navigates back to their browser from this page, they will re-trigger the logic that redirected them and will not be able to easily return to their preceding page. Yikes!
We generally don't want 404 errors to appear to have redirected the user at all, so we need to tell the router to not update our router location for this transition. We can do that by passing along the skipLocationChange option in our navigateByUrl redirect.