Search code examples
angularangular5angular-httpclient

Why must an Angular component clone an object returned by a service?


I'm going through the HttpClient page in the Angular Fundamentals section, and I was wondering why the component must clone the object received from the service that makes the HTTP calls?

The specific config.component.ts code block on the page (in this section) that I'm talking about is this one:

config: Config;

showConfig() {
  this.configService.getConfig()
    // clone the data object, using its known Config shape
    .subscribe(data => this.config = { ...data });
}

Solution

  • Because otherwise you would breach so called "data encapsulation" concept and your app might behave very weird. Service.ts class is a singleton (as usual) and all components that injects it, shares the same instance of it.

    So in all those components, this.configService.getConfig().subscribe(data => , data object is a one object. And if components doesn't clone it, just assigns its reference, and later someone mutates that data, some weirdness would begin because in component this.config is considered as a static object (after subscription completes) and if you don't clone it, it would reference to the data from your service which is a dynamic object.

    And in general, Javascript assigns objects by reference, so its always safer to clone things and keep data separate and mutate things in one place - so called, data store. Angular service.ts is an equivalent to the data store.

    Thats how I would explain it. Would love to see more answers.