gpt4 book ai didi

angular - 使用 TypeScript 在 Angular 管道中使用 MapToIterable

转载 作者:行者123 更新时间:2023-12-03 09:09:32 26 4
gpt4 key购买 nike

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

我有以下代码:

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”不是对象键,无法使用 Object.keys()in 运算符获取。

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

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

或者在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) 不同。

关于angular - 使用 TypeScript 在 Angular 管道中使用 MapToIterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43964440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com