1
votes

I have a component called 'orderDetails' and I'm trying to add a route guard to only render the component if the order has been placed, i.e. by:

status = 'PLACED'

I tried doing something like:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { OrderService } from './order.service';    

@Injectable()
export class RouteGuard implements CanActivate {

  orderId = 12345;  // mock id

  constructor(private router: Router, private orderService: OrderService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
     this.orderService.getOrderDetails(this.orderId).subscribe(data) => {
       if (data.status !== 'PLACED') { return false; } else { return true; }
     }
  }

}

But, this approach doesn't seem to work, maybe because I'm making an API call in the canActivate method. Is there another approach to implement this?

1
You need to return an observable of the resulting boolean; at the moment you just subscribe locally and don't return anything. Have you read through e.g. angular.io/guide/router#milestone-5-route-guards? - jonrsharpe

1 Answers

0
votes

Since you must return an Observable, you should not subscribe to your method getOrderDetailsbut map instead:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.orderService.getOrderDetails(this.orderId).map((data) => {
       return data.status === 'PLACED';
    }).catch(error => {
        return Observable.of(false);
    });
}