I'm still in the process of learning angular and typescript, so please forgive me for this question that may seem silly...
Currently, I have a list containing actors. When one of these actors is clicked on, it redirects to a detailed page with a URL structure like this:
localhost:4200/actors
After clicking on an actor, the URL changes to something like:
localhost:4200/actors/Jonas
Now, my goal is to verify if the chosen actor actually exists. If a user manually enters a random name in the URL, I want to redirect them back to the /actors page instead of displaying a blank page.
This is a snippet of how my component looks:
actor: Actor;
constructor(
private actorService: ActorService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit(): void {
this.route.params.subscribe(() => {
if (/* code to check if actor.name exists in the url */) {
this.route.paramMap.switchMap((params: ParamMap) =>
this.actorService.getActor(params.get('name')!))
.subscribe(actor => this.actor = actor);
} else {
this.location.go('/actors');
}
});
}
Does anyone have any insights on how I can accomplish this?