angular - Angular - 在我的组件中处理一个通用字典,我使用 HTTPClient 作为 HTTP 请求的响应返回
问题描述
我有一个向后端发出 POST 请求的服务(在 Angular 中):
import { HttpClient } from '@angular/common/http';
public getNamesPerTypes(): Observable<any> {
const observable = this.http.post<any>(AppConfig.baseUrl + getNamesPerTypesUrl, {});
return observable;
}
我的组件中的代码是:
getNames() {
this.connectionService.getNamesPerTypes()
.subscribe(
response => {
console.log(response);
},
err => console.log(err);
);
}
我从后端获得的对象如下所示:
{"$type":"System.Collections.Generic.Dictionary`2[[Types.ConnectionType, Types],[System.String, mscorlib]], mscorlib","Inner":"ConnectionF","Outer":"连接KLD"}
ConnectionType 是后端的枚举,它的一些值是:Inner、Outer。
如何在我的组件中获取通用字典的值:
"Inner":"ConnectionF",
"Outer":"ConnectionKLD"
到目前为止我所做的是:我已经导出了一个类:
export class NameAndConnectionType {
public name: string;
public connectionType: ConnectionType;
}
还导出了枚举 ConnectionType:
export enum ConnectionType{
Inner= 'Inner',
Outer= 'Outer'
}
现在我可能应该在我的 Angular 服务中包含以下内容:
http.post<Dictinary<ConnectionType, string>(AppConfig.baseUrl + getNamesPerTypesUrl, {});
或者使用我导出的类:NameAndConnectionType
代替:
http.post<any>
但我认为 TypeScript 中没有可用的 Dictionary 类型。
同样,我如何在我的组件中获取通用字典的值并使用它们。例如,使用控制台日志我想在浏览器的控制台中看到以下内容:
内部连接的名称是:ConnectionF
外部连接的名称是:ConnectionKLD
非常感谢您的帮助!
解决方案
解决这个问题的方法很少。我更喜欢使用 Map<> 它看起来像这样:
http.post<Map<T, U>(AppConfig.baseUrl + getNamesPerTypesUrl, {});
或者创建您自己的界面以供将来使用。
interface ConnectionTypeMap{
connection: {[key: string]: string};
}
或者
interface ConnectionTypeMap{
connection: Map<string, string>;
}
然后将其隐含到您的变量中
variable: ConnectionTypemap;
//////
http.post<ConnectionTypemap>(AppConfig.baseUrl + getNamesPerTypesUrl, {});
推荐阅读
- javascript - WebRTC STUN/TURN 分配请求超时
- javascript - 将多个输入序列化为单个参数
- java - Spring Boot 数据休眠事务管理器
- image - React Native Image 组件不会在 iOS 14 上从外部 url 渲染图像
- python - 无法使用 Zoom API 创建会议(响应代码 200)
- pine-script - 如果警报条件为真,如何在图表上绘制形状
- extjs - 分机 JS | 下载带有附加数据的图表
- javascript - 通过 Javascript 将 PDF 转换为“仅图像”
- java - 如何在类之间调用数组?
- python - 并行处理比串行处理花费更长的时间并跳过处理少量条目