Подтвердить что ты не робот

Эквивалент angular.equals в angular2

Я работаю над переносом проекта angular 1 на angular 2. В проекте angular 1 я использовал angular.equals для сравнения объектов angular.equals($ctrl.obj1, $ctrl.newObj);, я искал онлайн для эквивалентного метода в angular 2, но не смог найти никакого совпадающего результата.

4b9b3361

Ответ 1

@Günter Да, вы правы, нет эквивалента в angular2. При поиске больше я нашел стороннюю библиотеку loadash, которая будет выполнять ту же работу, что и angular.equals и syntex одинаково как angular одна и эта библиотека решает мою проблему

Выдержка кода из документации loadash

var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false

Ответ 2

Я переписал Ariels ответ (спасибо!), чтобы быть TSLINT-дружественным. Вы также можете сохранить некоторые из них, используя else, если, но я думаю, что это более понятно. Возможно, кому-то это тоже нужно:

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;
  }
}

Ответ 3

Вместо того, чтобы писать функцию для итерации объектов, вы можете просто использовать JSON.stringify и сравнить две строки?

Пример:

var obj1 = {
  title: 'title1',
  tags: []
}

var obj2 = {
  title: 'title1',
  tags: ['r']
}


console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));


console.log(JSON.stringify(obj1) === JSON.stringify(obj2));

Ответ 4

В Angular 2 вы должны использовать чистый JavaScript/ TypeScript для этого, чтобы вы могли добавить этот метод к некоторой службе

private static equals(x, y) {
    if (x === y)
        return true;
    // if both x and y are null or undefined and exactly the same
    if (!(x instanceof Object) || !(y instanceof Object))
        return false;
    // if they are not strictly equal, they both need to be Objects
    if (x.constructor !== y.constructor)
        return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

    let p;
    for (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 (!RXBox.equals(x[p], y[p]))
            return false;
    }
    for (p in y) {
        if (y.hasOwnProperty(p) && !x.hasOwnProperty(p))
            return false;
    }
    return true;
}

Ответ 5

a = { name: 'me' }
b = { name: 'me' }
a == b // false
a === b // false
JSON.stringify(a) == JSON.stringify(b) // true
JSON.stringify(a) === JSON.stringify(b) // true