简体   繁体   中英

modifying objects passed from component to service

I'm trying to refactor my code by putting common component methods into a shared service, however I'm not sure why I can't seem to overwrite a component's public object property passed to the service, although I do appear to be able to modify specific object properties.

To be specific this doesn't work:

Component:

   public data: any;    

    ngOnInit(): void {
       loadData(this.data);
       console.log(this.data); // <-- returns undefined
    }

Service Method:

loadData(data) {
    data = {test:'test'};
}

HOWEVER, if i were pass an object like { test: 'test' } to the service and just modify it in the service (eg set data.test = 'test2'), that appears to work...the component will have the modified value, as I would expect.

My question is, why doesn't can't I assign a new object to the object passed to the service, given that objects are supposedly passed by reference? Is angular doing something to protect the component property from mutating, and if so, can it be by passed?

btw, I understand I could simply return a value from loadData and do the assignment in the component, however, this doesn't help with more complicated methods that I want to refactor, that may have multiple objects being passed to the service and modified in the service method.

Any insights appreciated.

-S. Arora

You still can update your component data. But it would look like this:

loadData(data) {
    data.test = 'test';
}

Since you only want to override just object's property, this would be enough. Although I would add condition to check if object exists since without checking this would throw error. So perhaps:

loadData(data) {
  if (data) {
    data.test = 'test';
  }
}

Why your case didn't work, I'm not 100% confident, but it might be because you're trying to assign a completely new object (new reference) while in my case the reference stays the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM