Jayson
Jayson

Reputation: 129

How to return service by key

I am new to Angular and Typescript. I have saw this pattern and don't know what it mean.

  constructor(
    private workoutService: WorkoutService,
    private authService: AuthService
  ) {}

  private facadeSvc(key: svc) {
    return {
      [svc.AUTH]: this.authService,
      [svc.WORKOUT]: this.workoutService,
    }[key];
  }

  logToConsole(key: any) {
    return this.facadeSvc(key).log();
  }
}

enum svc {
  WORKOUT = 'WORKOUT',
  AUTH = 'AUTH',
}

What does facadeSvc(key: svc) function do??

In WorkoutService and AuthService had implement log() function to log some message to console. Therefore in other component, I only need to inject FacadeService and pass in the key, it will automatic call to the correct Service.

Does anyone know what this pattern call??

Thank in advance if anyone can explain to me.

Upvotes: 0

Views: 119

Answers (1)

anoop
anoop

Reputation: 3822

What does facadeSvc(key: svc) function do ?

This function return the instance of 'authService' or 'workoutService' depending on the key provided. Those instances are already available to facadeSvc method by angular dependency injection (via constructor). afterwards, by that instance you can access log() method of respective service.

Does anyone know what this pattern call??

It is mix of Facade pattern and Chain of responsibility.

Upvotes: 1

Related Questions