加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

迭代在Angular 2中的TypeScript字典

发布时间:2020-12-17 08:44:43 所属栏目:安全 来源:网络整理
导读:我试图做一些事情在Angular 2 Alpha 28,我有一个问题与字典和NgFor。 我有一个TypeScript中的界面,如下所示: interface Dictionary { [ index: string ]: string} 在JavaScript中,这将转换为一个对象,数据可能如下所示: myDict={'key1':'value1','key2
我试图做一些事情在Angular 2 Alpha 28,我有一个问题与字典和NgFor。

我有一个TypeScript中的界面,如下所示:

interface Dictionary {
    [ index: string ]: string
}

在JavaScript中,这将转换为一个对象,数据可能如下所示:

myDict={'key1':'value1','key2':'value2'}

我想迭代这一点,并尝试这:

<div *ngFor="(#key,#value) of myDict">{{key}}:{{value}}</div>

但没有效果,下面没有一个工作:

<div *ngFor="#value of myDict">{{value}}</div>
<div *ngFor="#value of myDict #key=index">{{key}}:{{value}}</div>

在所有情况下,我得到错误像“意外的令牌”或“不能找到’iterableDiff’管道支持对象”

我在这里失踪了什么?这不可能了吗? (第一个语法在Angular1.x中有效),或者是迭代一个对象的不同语法?

它似乎他们不想支持ng1的语法。

根据Mi?koHevery(reference):

Maps have no orders in keys and hence they iteration is unpredictable.
This was supported in ng1,but we think it was a mistake and will not
be supported in NG2

The plan is to have a mapToIterable pipe

<div *ngFor"var item of map | mapToIterable">

所以为了迭代你的对象,你将需要使用“管道”。
目前没有实施的pipe。

作为解决方法,下面是一个小例子,它遍历键:

零件:

import {Component} from 'angular2/core';

@Component({
  selector: 'component',templateUrl: `
       <ul>
       <li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
       </ul>
  `
})
export class Home {
  myDict : Dictionary;
  constructor() {
    this.myDict = {'key1':'value1','key2':'value2'};
  }

  keys() : Array<string> {
    return Object.keys(this.myDict);
  }
}

interface Dictionary {
    [ index: string ]: string
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读