angular - 使用 Angular 的 HttpClient 请求的安全方法是什么?
问题描述
官方Angular HttpClient 指南建议通过以下方式构建 HTTP 请求服务:
getConfig() {
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}
但也提供以下免责声明:
指定响应类型是对 TypeScript 的声明,它应该将您的响应视为给定类型。这是一个构建时检查,并不能保证服务器会实际响应这种类型的对象。由服务器确保返回服务器 API 指定的类型。
虽然我喜欢让服务返回定义明确的类型的主要概念,但免责声明表明,这对于没有人可以依赖某些外部软件系统响应格式的现实世界来说还没有完全准备好。
在 Angular 中实现 HTTP 请求服务的最佳实践是什么,它将可靠地返回预期类型的对象(在当前示例中Config
)或提供处理错误的方法?
解决方案
Angular 可以协助类型声明。但是要拥有完整的类型断言,您可以利用 Typescript 的断言功能。一种快速的方法是使用类型谓词来使用类型保护。
private isConfig(config: Config | any): config is Config {
return (config as Config).<property> !== undefined;
}
<property>
占位符必须替换为特定于该Config
类型的属性。然后您可以使用以下命令在运行时断言类型
import { of, throwError } from 'rxjs';
import { switchMap } from 'rxjs/operators';
getConfig() {
return this.http.get<Config>(this.configUrl).pipe(
switchMap(response => {
if (this.isConfig(response)) {
return of(response);
} else {
return throwError('The reponse is not of type Config');
}
}
);
}
推荐阅读
- bootstrap-4 - Blazor 登录控件在手机上消失
- amazon-web-services - Docker - AWS EC2 上的 springboot
- java - 在 Java 中使用回溯递归打印字符串的所有子序列
- r - 在 R 中矢量化 for 循环
- php - 如何使用雄辩的“with”来传递多个数组的数组以进行循环
- linux - 如何在 Jenkins Pipeline 中获取文件扩展名
- c# - 为什么将新项目添加到列表时,它会用索引 0 处的项目替换它,而不是在末尾添加新项目?
- angular - Angular 自定义验证器未将 FormArray 标记为无效
- unity3d - How do I get the dropdown that called my OnListener handler?
- bash - 生成包含在列表中命名的 shell 变量的 JSON 映射