How to set component properties for different routes?

Viewed 366

I have a top-nav component in my Angular App, in three of routes i have to show the cart in that component, till now i was using a service with BehaviourSubject and when i was navigating like in Products route i was setting it to true and then in my top-nav i was checking that if it's true i had to show the cart.

But now i have to find another approach, something inside top-nav component that detect if i'm in "products" route to show the cart else if i'm in "shop" route to hide it as i'm using reuse route and i'm unable to set BehaviourSubject on navigation back in "products"

Which would be the best way to do the following?

in constructor of top-nav i have the following:

cartService.isCartEnabled.subscribe((data) => (this.cart = data));

and then in html i'm checking if cart is true i'm showing the cart icon.

1 Answers

You could add attributes to your route, then a route Guard to set the attribute on navigation.

Here a link to angular docs about configuring the route attributes

You add a data node with some attributes to the route you want to display the cart on:

...
  {
    path: 'with-cart',
    component: YourComponent,
    data: { displayCar: true }
  },
  {
    path: 'without-cart',
    component: YourComponent,
  },
...

using a resolver (more details in angular docs) you could read this data parameter and set it on the service:

@Injectable({
  providedIn: 'root',
})
export class CartResolverService implements Resolve<boolean> {
  constructor(private yourService: YourService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    this.yourService.setDisplayCart(route.data.displayCart)
    
    return of(route.data.displayCart === true);
  }
}

and reconfigure the routes again with this resolver:

  {
    path: 'with-cart',
    component: YourComponent,
    data: { displayCar: true },
    resolve: {
      cartResolver: CartResolverService,
    },
  },
  {
    path: 'without-cart',
    component: YourComponent,
    resolve: {
      cartResolver: CartResolverService,
    },
  },

And, your nav needs to be subscribed to this service, so it can action the changes.

Related