What's alternative to angular.copy in Angular
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 Angular.
EXCEPTION: ReferenceError: angular
is not defined
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 }
Till we have a better solution, you can use the following:
duplicateObject = <YourObjType> JSON.parse(JSON.stringify(originalObject));
EDIT: Clarification
Please note: The above solution was only meant to be a quick-fix one liner, provided at a time when Angular 2 was under active development. My hope was we might eventually get an equivalent of angular.copy()
. Therefore I did not want to write or import a deep-cloning library.
This method also has issues with parsing date properties (it will become a string).
Please do not use this method in production apps. Use it only in your experimental projects - the ones you are doing for learning Angular 2.
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
链接地址: http://www.djcxy.com/p/40680.html上一篇: 克隆对象