我想知道如何将
new Set ()
javascript 对象与 Angular“新”信号一起使用。由于我已经玩了很长时间了,所以我决定将其发布在这里。只需简单的添加和删除即可。
set = signal (new Set ()); // initialize as an empty set, no need the <Set> because it's implicit.
toggleOptionFromSet (option: string) { // just a function to toggle an option in and out of a signal Set.
if (this.set ().has (option)) { // if the set contains the value...
this.set.update (set => { // deletes the option of the set.
// you cannot return set.delete (option) because it returns a boolean and update needs to return a Set.
set.delete (option)
return set;
});
console.log (this.set ()); // you see that the option has been erased.
} else { // if the set () does not contain the option...
this.set.update (set => set.add (option)); // this actually returns a new set, so, as you might know, you don't need to return it explicitly.
console.log (this.set ()); // the option has been added to the set.
}
}
希望它对某人有帮助!
如果需要,您可以创建自己的setSignal。 下面的示例将创建一个返回 Set 的 values 的信号。 信号通过分配给信号的函数进行更新,并镜像Set的函数。 mutate 功能使输出信号和 Set 存储保持同步。
import { createSignal, SIGNAL, signalSetFn } from '@angular/core/primitives/signals';
function setSignal<T>(initial?: Iterable<T> | null | undefined) {
const store = new Set<T>(initial);
const $output = createSignal(store.values());
const outputNode = $output[SIGNAL];
return Object.assign($output, {
add: (value: T) => mutate(store.add.bind(store, value)),
clear: () => mutate(store.clear.bind(store)),
delete: (value: T) => mutate(store.delete.bind(store, value)),
has: store.has.bind(store)
});
function mutate(mutator: () => void) {
mutator();
signalSetFn(outputNode, store.values())
}
}