Home » Javascript » How to put a route guard on a promise result

How to put a route guard on a promise result

Posted by: admin November 1, 2017 Leave a comment


In angular 4, I’m trying to implement a 404 page whenever a nonexistent id is being navigated to. I get my data via a promise. with my current logic, I am going to always get true for the value of ‘eventExists’ since a promise is being returned. So my code works if the route didn’t return a promise, but since it is a promise I need to do something different, but I’m not sure what. Here is my code:

import { Router, ActivatedRouteSnapshot, CanActivate }  from "@angular/router"
import { Injectable }                                   from "@angular/core"
import { TestelementService }                           from '../testelement/testelement.service'

export class RouteActivator implements CanActivate {
    constructor(private testelementService: TestelementService, private router: Router) {

    canActivate(route: ActivatedRouteSnapshot) {
        const eventExists = !!this.testelementService.gettestelement(+route.params['id']);

        if (!eventExists) { // this will not work correctly since the promise is going to exist. you need to handle this with promises.
            console.log("does not exist");
        } else {
        return eventExists;