Home > Blockchain >  (Angular) Why would you want multiple instances of the same service?
(Angular) Why would you want multiple instances of the same service?

Time:12-02

I might be missing something, and people usually ask "How to" not "Why to" whenever I google it

But what's the point of actually creating multiple instances of the same service where each instance has the same functions, same variables?

CodePudding user response:

To hold state.

Imagine you have an application, which has multiple tabs. Let's say they display car information, so each tab has a different car. You provide service in "root tab" component, so instance of that service will be available to all sub-components/services within that that tab, and not outside. This way you write service that stores data of one car, which reduces service complexity.

Small example

@Injectable()
export class CarService {
  color = '';
}
@Component({
  ...
  providers: [CarService]
})
export class TabComponent {
  constructor(private car: CarService) {}
  getColor() { return this.car.color }
}

This way you can have

TabComponent
  getColor() -> red
TabComponent
  getColor() -> blue
TabComponent
  getColor() -> black
  • Related