angularjs - Echivalentul lui angular.equals în angular2
Lucrez la migrarea unui proiect Angular 1 către Angular 2. În proiectul Angular 1 foloseam angular.equals pentru compararea obiectelor angular.equals($ctrl.obj1, $ctrl.newObj);, am căutat online un echivalent în Angular 2, dar nu am găsit niciun rezultat corespunzător.
Răspuns #1
@Günter Da, ai dreptate, nu există echivalent în Angular2. În timp ce căutam mai departe, am găsit biblioteca terță parte lodash care va face aceeași treabă ca angular.equals și sintaxa este aceeași cu cea a lui Angular, iar această bibliotecă îmi rezolvă problema
Exemplu de cod din documentația lodash
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
Răspunsul #2
Am rescris răspunsul lui Ariel (mulțumesc!) pentru a fi compatibil cu TSLINT. De asemenea, poți economisi niște continuări folosind else if, dar cred că aceasta este mai clar. Poate altcineva are nevoie și de asta:
export function deepEquals(x, y) {
if (x === y) {
return true; // if both x and y are null or undefined and exactly the same
} else if (!(x instanceof Object) || !(y instanceof Object)) {
return false; // if they are not strictly equal, they both need to be Objects
} else if (x.constructor !== y.constructor) {
// they must have the exact same prototype chain, the closest we can do is
// test their constructor.
return false;
} else {
for (const p in x) {
if (!x.hasOwnProperty(p)) {
continue; // other properties were tested using x.constructor === y.constructor
}
if (!y.hasOwnProperty(p)) {
return false; // allows to compare x[ p ] and y[ p ] when set to undefined
}
if (x[p] === y[p]) {
continue; // if they have the same strict value or identity then they are equal
}
if (typeof (x[p]) !== 'object') {
return false; // Numbers, Strings, Functions, Booleans must be strictly equal
}
if (!deepEquals(x[p], y[p])) {
return false;
}
}
for (const p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
return false;
}
}
return true;
}
}
