本文介绍了带有 TypeScript 的 Angular 管道中的 MapToIterable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 Angular 中实现管道.在意识到 ngFor 不适用于地图之后.一些研究让我相信未来的功能会解决这个问题,但同时 mapToIterable 管道就是答案.

Trying to implement a pipe in Angular. After realizing ngFor wouldn't work with maps. Some research led me to believe that future features were coming to deal with that but in the meantime a mapToIterable pipe was the answer.

我有以下代码:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'mapToIterable'
})
export class MapToIterablePipe implements PipeTransform  {
  transform(map: Map<string, Object>, args: any = []): any {
    const a: any[] = [];
    console.log(map.keys());  // <- works as expected
    for (const k in map) {
      if (map.has(k)) {
        console.log("hello");  // <- never executes
        console.log(k);
        a.push({key: k, val: map.get(k)});
      }
    }
    console.log(a); // <- always empty
    return a;
  }
}

export const MAPTOITERABLE_PROVIDERS = [
  MapToIterablePipe
];

map.keys() 给了我一个正确键的列表,但其他的都不起作用.

map.keys() gives me a list of correct keys, but nothing else works.

关于如何诊断为什么我的循环没有正确填充数组的任何建议?

Any suggestion on how to diagnose why my loop isn't filling the array correctly?

推荐答案

Map 'keys' 不是对象键,不能用 Object.keys()in 运算符.

Map 'keys' are not object keys and cannot be obtained with Object.keys() or in operator.

考虑到 map.keys() 返回一个可迭代对象,它应该是

Considering that map.keys() returns an iterable, it should be

for (const key of Array.from(map.keys())) {
  // this check is unneeded
  // if (map.has(k)) {
  ...
}

或者在 TypeScript 2.3 带有 downlevelIteration 选项

Or in TypeScript 2.3 with downlevelIteration option,

for (const key of map.keys()) { ... }

或者只是

const a: any[] = Array.from(map.entries()).map(([key, val]) => ({ key, val }));

由于 TypeScript 实现扩展运算符的方式,[...iterable] 在 2.2 及更低版本中的工作方式与 Array.from(iterable) 不同.

Due to how TypeScript implements spread operator, [...iterable] won't work the same way as Array.from(iterable) in 2.2 and lower.

这篇关于带有 TypeScript 的 Angular 管道中的 MapToIterable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:51