Angular 4: Handling ID Not Found

Viewed 1847

In Angular, I understand how to use a wildcard routing to show a custom 404 page. However that only covers the case of a non-existing component.

What about the case where the user reached an existing component, but passed a non-existing ID?

For example /widgets/12345 where 12345 does not exist in the database. What is the best practice in this case to show a 404?

I managed to redirect the user to a 404 page by catching the error. But that does not seem right: you don't usually get redirected for a 404, you expect to stay on the same URL but with a 404 page instead.

1 Answers

If in angular it was possible to send a 404 status error then it would be easier to handle this type of situation. But, in angular there is no point of returning a 404 status error because in angular you're not actually making any http request while browsing through the component.

To get around this, you can use Angular resolve to Router Guards find out whether the route data id is existed. If it is not existed then redirect to your 404 page.

 @Injectable()
 export class checkIdExistence  implements CanActivate {

    constructor(private router: Router,
                private route: ActivatedRoute,
                private yourService: YourService) {
    }

    canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) 
    {
       return this.route.params
          .mergeMap(
           (params: Params) => {
              const newId = params['id'] ? +params['id'] : '';
              return this.yourService.checkExistence(newId)
                   .map((myInstance: any) => {
                       if (myInstance && myInstance.id ) {
                         return true;
                       }
                      this.router.navigate(['/404-url']);
                      return false;
                   })
                  .catch(() => Observable.of(false));
         });

    }
 }
Related