2017-02-24 69 views
1

當我在一個組件內創建一個變量並將其從一個服務分配給一個數組時。並且從組件中更改數組,它也會從服務中更改數組。我如何防止這一點。從服務分配給數組的組件變量如何防止這種情況發生變化?

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。

+0

http://stackoverflow.com/questions/35504310/deep-copy-an-array-in-angular- 2-打字稿 – tymeJV

回答

1

我想包你在一個對象數組常量並使用Object.assign複製對象:

export class MemoryService { 
    dataStore: { posts: any[] }; 

    get posts() { 
     // make a deep copy of the object and return it 
     return Object.assign({}, this.dataStore).posts; 
    } 
相關問題