ricksmt
ricksmt

Reputation: 899

Dependency in RouteReuseStrategy

I'm trying to implement a custom RouteReuseStrategy. Resources like this answer have been invaluable in understanding what's going on, but I find myself in a predicament:

My strategy has a dependency on one of my services which it uses to know if the user logs out at which point it clears the cached routes. It varies a little depending on what I try, but I seem to have the same issue as posed in this question. Unfortunately, the corresponding answer to that question uses a deprecated method, and when I try alternatives I somehow get a different instance of the service than what the rest of the application gets.

For reference I've got something like this:

export class CustomReuseStrategy implements RouteReuseStrategy {
    // Cache of reusable routes.
    protected handlers: {[key: string]: DetachedRouteHandle} = {};

    constructor(private userService: UserService) {
        this.userService// When the user
            .logoutEvent$// logs out,
            .subscribe(() => this.handlers = {});// clear the cache.
    }

    // Implementations of RouteReuseStrategy methods.
    // ...
}

How can I make sure the service is treated as a singleton? Or is there another way I should go about this?

Upvotes: 4

Views: 3024

Answers (1)

vinnyo
vinnyo

Reputation: 61

Here's another way you can consider. This works for me in Angular 5 but should also work in some older versions.

Implement a method to clear the handlers in your CustomReuseStrategy.

export class CustomReuseStrategy implements RouteReuseStrategy {
   // Cache of reusable routes.
   protected handlers: {[key: string]: DetachedRouteHandle} = {};

   clearHandlers(){
      this.handlers = {};
   }

   // Implementations of RouteReuseStrategy methods.
   // ...

}

Since the RouteReuseStrategy is a service, you could inject it into your UserService service and call the method to clear your handlers when your service performs a login/logout.

Note that you would need to cast the injected service to your custom class to call your custom method.

export class UserService{

   constructor(private routeReuse:RouteReuseStrategy){}

   doLogin(){
      // After login is successful, clear the handlers
      //...
      (<CustomReuseStrategy>this.routeReuse).clearHandlers();
   }
}

Upvotes: 4

Related Questions