为什么我的Angular KeyValueDiffer先前值为空?

时间:2019-04-10 17:07:41

标签: angular

背景-我有另一个组件,该组件在发出数据之前会深克隆数据并对其进行更改,因此,为了使键值的引用保持不变,我至少在现在已经为此组件创建了一个深克隆。 / p>

由于某种原因,第一次调用getChangedNewRoles会返回我所有的角色。之后,它可以正常工作。我已经尽力确保引用不会改变,所以这对我来说已经毫无意义。

ngOnInit(): void {
    const data = ... get my data
    const cloned = deepClone(data);
    this.setupKeyValueDiffers(cloned);
}

getChangedNewRoles(newData: Role[]): Role[] {
    const changedRoles: Role[] = [];

    for (const differ of this.roleDiffers) {
        const existingRoleId = differ[0];
        const existingRoleDiffer = differ[1];

        const matchingNewDataRole = newData.find(x => x.id === existingRoleId);
        const matchingOriginalDataRole = this.cloned.find(x => x.id === existingRoleId);

        // key value differ only works properly if the objects being compared have the same reference
        // but we dont want to change AllRoles before saving so we store a deep clone internally here as well
        Object.assign(matchingOriginalDataRole, matchingNewDataRole);

        const changes = existingRoleDiffer.diff(matchingOriginalDataRole);
        if (changes) {
            changedRoles.push(matchingNewDataRole);
        }
    }

    return changedRoles;
}


private setupKeyValueDiffers(data: Role[]): [string, KeyValueDiffer<string, any>][] {
    const differs: [string, KeyValueDiffer<string, any>][] = [];

    for (const role of data) {
        const differ = this.keyValueDiffers.find(role).create();
        differs.push([role.id, differ]);
    }

    return differs;
}

编辑:

我注意到getChangedNewRoles中existingRoleDiffer的内部记录属性为空,因此我将setupKeyValueDiffers更改为此:

private setupKeyValueDiffers(data: Role[]): [string, KeyValueDiffer<any, any>][] {
    const differs: [string, KeyValueDiffer<any, any>][] = [];

    for (const role of data) {
        const differ = this.keyValueDiffers.find(role).create();
        differ.diff(role as any);
        differs.push([role.id, differ]);
    }

    return differs;
}

我在这里调用diff,并且正确地填充了records属性。现在我的代码有效了...

当我第一次创建它而没有在结尾处调用.diff时,编辑所有属性都为null。那肯定是没有道理的。

1 个答案:

答案 0 :(得分:0)

this.keyValueDiffers.find(role)

仅检查参数类型是否可以应用不同。这就是为什么它需要初始diff调用的原因。