mardi 19 janvier 2021

Best way for service communication in angular

What is the best way to communicate between services in angular

For Example:

1- I have one service called Market that get an array of fruits let's say: Orange, Apple and Banana

2- Let's consider each fruit is a service containing string:

export class OrangeService {
name:string;
}


export class AppleService {
name:string;
}

export class BananaService {
name:string;
}

So what is better to do in order to change the property in each service:

1- Create a fruit service:

example:

   export class FruitService {
    
  constructor(private orangeService: OrangeService, 
  private appleService: AppleService,  
  private bananaService: BananaService )
  
  setFruitName(name:string){
  switch(name) {
  case 'Orange':
  this.orangeService.name = 'orange1';
  break;
  case 'Banana':
  this.bananaService.name = 'banana1';
  break;
  case 'Apple':
  this.appleService.name = 'apple1';
  break;
    }
  }
}

2- Or Directly Use dependency injection in the Market service and write the same logic for setFruitName(name:string)

if there is a more dynamical way with the escape of switch or a more optimal way I will appreciate the help.

Aucun commentaire:

Enregistrer un commentaire