How to inject the right service depending on the context of UI?

447 views Asked by At

I have a component that renders a list of users (it injects its related service called UserService) in a dedicated module

I have another component that renders a list of Products (inject its related service called ProductService) in a dedicated module

In each row of the previous lists, I have another component that renders a contextual button with a dropdown that displays a list of actions (Edit, Remove etc...) (this is a shared component between the two lists)

From the shared component I would like to call a related service method (UserService.method(), ProductService.method()) depending on which list is rendered, How can I do this? How can I inject the related service I need in the specific context? Can I abstract the service to inject inside the shared component?

I would like to avoid injecting all services into the shared component.

I'm a little lost. I hope my explanation was clear. Thanks

Here the pseudocode

/*********** USER MODULE ***********/
@Injectable({
  providedIn: 'root',
})
export class UserService{
    dosomething() {}
}

@Component(...)
    export class UserListComponent implements OnInit {
      users: Users = [];
      constructor(private readonly userService: UserService) {}
    
      ngOnInit(): void {
        this.users = this.userService.users;
      }
    }


/*********** PRODUCT MODULE ***********/
@Injectable({
  providedIn: 'root',
})
export class ProductService{
    dosomething() {}
}

@Component(...)
export class ProductListComponent implements OnInit {
      products: Products = [];
      constructor(private readonly productService: ProductService) {}
    
      ngOnInit(): void {
        this.products = this.productService.product;
      }
}
 

/*********** CORE MODULE ***********/
@Component(...)
export class DropdownActionButton {
    
    constructor(
        private readonly userService: UserService,
        private readonly productService: ProductService,
        //  ... I have to add a new service as dependency if a new list is created ...
      ) {}
      
        handleClick(){
            if('you are in the user list') {
            userService.dosomething()
            }
    
            if('you are in the product list') {
            productService.dosomething()
            }
        // ... I have to do a new if if a new list is create ....
        }
}
1

There are 1 answers

0
akkonrad On

you can define a provider in your module that uses the service implementation you'd like to use. Check multi providers topic: https://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html So in the user module, you will provide user service, in the product module, you will provide product service. Make sure that your services are implementing the same interface.