在 Angular 的 HttpClient 中观察的正确方法(按书)
Proper way to approach observe in HttpClient of Angular (by the book)
在 docs for HttpClient
中提到了 HttpObserve
。然而,当我为它 Google 时,它似乎(基于不同的博客和论坛)已被删除。它绝对不存在于 Angular 9 中(至少在 @angular/common/http
下)。不同的来源提供了不同的建议,我觉得其中假设多于知识。
根据例如this declaration 应该提供 HttpObserve
类型的内容(当然,大多数人可能会跳过)。我准备了以下示例。
const headers: HttpHeaders = new HttpHeaders();
const observe: HttpObserve = null;
const params: HttpParams = new HttpParams();
const reportProgress = false;
const responseType = "json";
const withCredentials = true;
VS Code 将第二行标记为不正确,因为无法识别类型。我找不到关于如何处理它的可靠、可靠的信息来源,所以我变得谨慎。从 5 日到 8 日以来,根据版本的不同,似乎也有不同的反应,而目前的 9 日则没有那么多。有时间深入研究一下,特此请教。
should/could 作为 observe
参数的类型提供什么(如果有的话)?
你可以看到它的定义in the source code (you can find it via GitHub search):
export type HttpObserve = 'body'|'events'|'response';
或在您链接到的 HttpClient
API 文档中的各种重载中列出。它 在 Angular 9 中存在 (参见 9.1.x tag),只是没有作为模块定义的一部分公开。
, this is a string literal type; the value must be one of those three string literals. For example, in the HTTP guide 他们显示它被设置为 'response'
以读取整个响应(而不是默认的 'body'
):
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
就您代码中的使用而言,您拥有与我 相同的所有选项来定义该值和您的选项对象。
在 docs for HttpClient
中提到了 HttpObserve
。然而,当我为它 Google 时,它似乎(基于不同的博客和论坛)已被删除。它绝对不存在于 Angular 9 中(至少在 @angular/common/http
下)。不同的来源提供了不同的建议,我觉得其中假设多于知识。
根据例如this declaration 应该提供 HttpObserve
类型的内容(当然,大多数人可能会跳过)。我准备了以下示例。
const headers: HttpHeaders = new HttpHeaders();
const observe: HttpObserve = null;
const params: HttpParams = new HttpParams();
const reportProgress = false;
const responseType = "json";
const withCredentials = true;
VS Code 将第二行标记为不正确,因为无法识别类型。我找不到关于如何处理它的可靠、可靠的信息来源,所以我变得谨慎。从 5 日到 8 日以来,根据版本的不同,似乎也有不同的反应,而目前的 9 日则没有那么多。有时间深入研究一下,特此请教。
should/could 作为 observe
参数的类型提供什么(如果有的话)?
你可以看到它的定义in the source code (you can find it via GitHub search):
export type HttpObserve = 'body'|'events'|'response';
或在您链接到的 HttpClient
API 文档中的各种重载中列出。它 在 Angular 9 中存在 (参见 9.1.x tag),只是没有作为模块定义的一部分公开。
'response'
以读取整个响应(而不是默认的 'body'
):
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
就您代码中的使用而言,您拥有与我