What's alternative to angular.copy in Angular

后端 未结 15 1115
忘掉有多难
忘掉有多难 2020-11-29 00:43

How can I copy an object and lose its reference in Angular?

With AngularJS, I can use angular.copy(object), but I\'m getting some error using that in An

相关标签:
15条回答
  • 2020-11-29 01:32

    Assuming you are using ES6, you can use var copy = Object.assign({}, original). Works in modern browsers; if you need to support older browsers check out this polyfill

    update:

    With TypeScript 2.1+, ES6 shorthand object spread notation is available:

    const copy = { ...original }
    
    0 讨论(0)
  • 2020-11-29 01:32

    For shallow copying you could use Object.assign which is a ES6 feature

    let x = { name: 'Marek', age: 20 };
    let y = Object.assign({}, x);
    x === y; //false
    

    DO NOT use it for deep cloning

    0 讨论(0)
  • 2020-11-29 01:32

    Use lodash as bertandg indicated. The reason angular no longer has this method, is because angular 1 was a stand-alone framework, and external libraries often ran into issues with the angular execution context. Angular 2 does not have that problem, so use whatever library that you want.

    https://lodash.com/docs#cloneDeep

    0 讨论(0)
  • 2020-11-29 01:33

    I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

      copyFactory = (() ->
        resource = ->
          resource.__super__.constructor.apply this, arguments
          return
        this.extendTo resource
        resource
      ).call(factory)
    
    0 讨论(0)
  • 2020-11-29 01:33

    You can clone the Array like

     this.assignCustomerList = Object.assign([], this.customerList);
    

    And clone the object like

    this.assignCustomer = Object.assign({}, this.customer);
    
    0 讨论(0)
  • 2020-11-29 01:35

    I needed this feature just form my app 'models' (raw backend data converted to objects). So I ended up using a combination of Object.create (create new object from specified prototype) and Object.assign (copy properties between objects). Need to handle the deep copy manually. I created a gist for this.

    0 讨论(0)
提交回复
热议问题