为什么要在 HttpClient 响应可观察对象上使用扩展运算符?
Why use the spread operator on an HttpClient response observable?
我在查看有关 Angular 的 HttpClient (https://angular.io/guide/http#error-handling) 的文档时发现了这个片段:
showConfig() {
this.configService.getConfig()
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error // error path
);
}
我很好奇为什么 data
对象在分配给 config
属性 之前就被传播了。这样做比简单地将数据对象直接分配给 this.config
有什么好处?
我也一直在想同样的事情。我想这只是一种很好的灵活做法。当您传播 ...data 时,它会复制每个 key/value 对,而 this.config 是现在保存复制对象的接收者。如果需要,您可以向 this.config 添加一些其他内容,例如 { ...data, ...moredata }
以下摘自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."
这对我来说很新,所以我绝不是权威,但这就是我收集的(如果我遗漏了什么请告诉我)。我现在在一些生产代码中使用这种技术。
我在查看有关 Angular 的 HttpClient (https://angular.io/guide/http#error-handling) 的文档时发现了这个片段:
showConfig() {
this.configService.getConfig()
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error // error path
);
}
我很好奇为什么 data
对象在分配给 config
属性 之前就被传播了。这样做比简单地将数据对象直接分配给 this.config
有什么好处?
我也一直在想同样的事情。我想这只是一种很好的灵活做法。当您传播 ...data 时,它会复制每个 key/value 对,而 this.config 是现在保存复制对象的接收者。如果需要,您可以向 this.config 添加一些其他内容,例如 { ...data, ...moredata }
以下摘自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."
这对我来说很新,所以我绝不是权威,但这就是我收集的(如果我遗漏了什么请告诉我)。我现在在一些生产代码中使用这种技术。