gpt4 book ai didi

angular - 为什么大多数 HttpClient API 类都定义不可变对象(immutable对象)?

转载 作者:太空狗 更新时间:2023-10-29 18:06:44 26 4
gpt4 key购买 nike

documentation for HttpClient声明以下关于不变性的内容:

Interceptors exist to examine and mutate outgoing requests and incoming responses. However, it may be surprising to learn that the HttpRequest and HttpResponse classes are largely immutable.

This is for a reason: because the app may retry requests, the interceptor chain may process an individual request multiple times. If requests were mutable, a retried request would be different than the original request. Immutability ensures the interceptors see the same request for each try.

我觉得很难理解这个解释。有人可以提供解释吗?

最佳答案

这个解释不懂就很难看懂the source code .在文章 Insider’s guide into interceptors and HttpClient mechanics in Angular 中对此进行了深入解释.

当你调用 http 的任何方法时,比如 get,Angular 会创建一个请求。然后这个请求用于启动一个可观察的序列,当订阅这个请求时通过拦截器链传递。这是作为序列处理的一部分完成的(非常简化的代码):

function get() {
let req: HttpRequest<any> = new HttpRequest<any>();
const events$ = of(req).pipe(concatMap((req: HttpRequest<any>) => {
// running request through interceptors chain
this.handler.handle(req);
}));
return $events;
}

这是来自消息来源的评论:

Start with an Observable.of() the initial request, and run the handler (which includes all interceptors) inside a concatMap(). This way, the handler runs inside an Observable chain, which causes interceptors to be re-run on every subscription (this also makes retries re-run the handler, including interceptors).

因此 $events 流是从 http 请求方法返回的并且可以重试。拦截器应始终从原始请求开始。如果请求是可变的并且可以在之前的拦截器运行期间修改,则不能满足此条件。因此请求及其所有组成部分应该是不可变的。

关于angular - 为什么大多数 HttpClient API 类都定义不可变对象(immutable对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47930218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com