首页 > 解决方案 > 在 Angular 中创建一个可观察的 Dictionary/HashMap(或 KeyValue 对)?

问题描述

我想创建一个可观察的 KeyPairValue(或 Map,但我不知道该怎么做)。

这是我的声明:

  private readonly subjectTokensKeyValue = new Subject<{ [key: string]: [value: string] }>();
  public readonly tokensKeyValue$ = this.subjectTokensKeyValue.asObservable();
  

现在我有一个方法可以将值传递给我的 observable

  public setTokens(tokens: { [key: string]: [value: string] }) {
    this.subjectTokensKeyValue.next(tokens);
  }
  

现在我需要初始化theTokens数组(但是,我不知道该怎么做!!!)

const theTokens = [];///HERE!!!

const token = {
    key: "theKey",
    value: "theValue",
};

theTokens.push(token);

后来我尝试传递值

this.setTokens(theTokens); /// HERE I Have a Problem

问题信息是

'{ key: any; 类型的参数 值:任何;}[]' 不能分配给 '{ [key: string]: [value: string]; 类型的参数 }'。

类型 '{ key: any; 中缺少类型 'string' 的索引签名;值:任何;}[]'.ts(2345)

我必须如何初始化theTokens

标签: angulardictionaryobservablesubject

解决方案


推荐阅读