A component variable that's assigned to an array from a service changes both ways how to prevent this?
本问题已经有最佳答案,请猛点这里访问。
当我在一个组件内创建一个变量并将其分配给一个来自服务的数组时。并从组件更改数组,它还从服务更改数组。我该怎么预防呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | export class PostComponent implements OnInit { posts: any; constructor( private memoryService: MemoryService, ){} // run code ngOnInit(): void { this.posts = this.memoryService.posts; this.posts.splice(1, 1); console.log(this.posts);// spliced console.log(this.memoryService.posts);// also spliced } } |
所以我希望它只拼接this.post数组,而不是来自this.memoryService的数组。
我将用对象文本包装您的数组,并使用
1 2 3 4 5 6 7 | export class MemoryService { dataStore: { posts: any[] }; get posts() { // make a deep copy of the object and return it return Object.assign({}, this.dataStore).posts; } |