首页 > 解决方案 > 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

非常感谢您的帮助!

标签: angulartypescripthttp

解决方案


解决这个问题的方法很少。我更喜欢使用 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, {});

推荐阅读