When updating a scope variable, update another with the same value Angular2

1

Good morning everyone.

I have a method that we say does something like this:

getAll(){
         this.commonServices.getAllList()
                           .subscribe(
                               res => {
                                    this.resultList= res;
                                    this.copieResultList= res;                               
                               },
                                err => {
                                    console.log("Error: " + err);
                                });

    }

So far so good. I call the service that will recover an array of objects and store its response in two scope variables. resultList and copieResultList . The problem is that below I have a method that does:

getOne(id: string){
        this.commonService.getOne(id)
                            .subscribe(
                                res => {
                                 console.log(this.resultList);
                                    this.resultList.length = 0;
                                    this.resultList= res;
                                 console.log(this.resultList);
                                },
                                err => {
                                    console.log("Prueba error: " + err);
                                });
    }

Here the problem begins. And is that the first console.log prints me the list as is logical. But the second one does not, the second one shows it to me empty. That is, having modified the resultList has also modified the copieResultList

  

The scope is not being modified by mistake in any other part of the code.

Any ideas?

    
asked by Findelias 09.03.2017 в 14:25
source

1 answer

3

More than a Scopes error, it is a programming concept error. When you dump the value of an object, do not return the object in the variable if you do not create a reference to it, which explains what is happening to you.

  

Once you pass the first capture, both point to the same space   of memory where that object is found.

When you get to the second image, you modify resultList but it also affects copieResultList because you are really modifying the object to which both are pointing.

    
answered by 10.03.2017 / 18:35
source