1

When I create a variable inside a component and assign it to an array from a service. And change the array from the component it also changes the array from the service. How do I prevent this.

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

    }

}

So what I want it is to only splice the this.post array and not the one from this.memoryService.

Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57

1 Answers1

1

I would wrap your array in an object literal and copy the object using 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;
    }
Michael Kang
  • 52,003
  • 16
  • 103
  • 135