首页 > 解决方案 > 使用 Angular 的 HttpClient 请求的安全方法是什么?

问题描述

官方Angular HttpClient 指南建议通过以下方式构建 HTTP 请求服务:

getConfig() {
  // now returns an Observable of Config
  return this.http.get<Config>(this.configUrl);
}

但也提供以下免责声明:

指定响应类型是对 TypeScript 的声明,它应该将您的响应视为给定类型。这是一个构建时检查,并不能保证服务器会实际响应这种类型的对象。由服务器确保返回服务器 API 指定的类型。

虽然我喜欢让服务返回定义明确的类型的主要概念,但免责声明表明,这对于没有人可以依赖某些外部软件系统响应格式的现实世界来说还没有完全准备好。

在 Angular 中实现 HTTP 请求服务的最佳实践是什么,它将可靠地返回预期类型的​​对象(在当前示例中Config)或提供处理错误的方法?

标签: angulartypescriptangular-httpclienttype-safety

解决方案


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');
      }
    }
  );
}

推荐阅读