Search code examples
angular2-observablesangular-httpclient

Why use the spread operator on an HttpClient response observable?


I was looking at the documentation on Angular's HttpClient (https://angular.io/guide/http#error-handling) and came across this snippet:

showConfig() { this.configService.getConfig() .subscribe( (data: Config) => this.config = { ...data }, // success path error => this.error = error // error path ); }

I'm curious as to why the data object is spread before being assigned to the config property. What is the advantage of doing this over simply assigning the data object directly to this.config?


Solution

  • I've been wondering the same thing too. I imagine it's just a good flexible practice. When you spread ...data it makes a copy of each key/value pair and this.config is the receiver that now holds the copied object. If you needed to, you could add some other stuff to this.config like { ...data, ...moredata }

    The following excerpt is taken from https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831

    "When the thing that is being spread is an object and the receiver is an object too, then the key-value pairs are copied together instead of just values. Mostly, spread operator with objects is used to make a copy of an existing object or to make a new object with more properties."

    This is pretty new to me, so I'm by no means an authority, but that's what I've gathered (tell me if I'm missing something). I'm using this technique now in some production code.