Issue
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?
Solution
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
Answered By - Bojan Kogoj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.