I have read that when passing objects as parameters in javascript (also inherited in Typescript) it is passed by reference.
Could that possibly cause memory leaks?
Let's assume a scenario where:
@Component({
selector: "customer-details",
templateUrl: "../html/customerDetails.template.html"
})
export class CustomerDetailsComponent {
customerData: Customer;
constructor(private customerService: CustomerService): void {}
saveCustomerInfo(): void {
this.customerService.saveCustomer(this.customerData);
}
}
Wouldn't that cause a memory leak, as the service now has a saved reference of a Component's attribute not allowing the Component to be garbage collected?
In any case, what is the best practice on such calls? Should we only pass temporary objects declared inside the functions via "let" or pass clones created by Object.create()?
Thank you very much in advance,
Dimitris
@Component({
selector: "customer-details",
templateUrl: "../html/customerDetails.template.html"
})
export class CustomerDetailsComponent {
customerData: Customer;
constructor(private customerService: CustomerService): void {}
saveCustomerInfo(): void {
this.customerService.saveCustomer(this.customerData);
}
}
In your example code, based on what you described in the rest of your question, I assume that the customerService.saveCustomer(customerData) call ends up putting its parameter (customerData) into an internal array.
This correctly means that the customerData object won't be garbage collected because now your customerService object has a reference to it. However, although the customerData object can't be garbage collected, the rest of the CustomerDetailsComponent can be garbage collected without an issue - the fact that someone else has a reference to one of its internal properties means that specific property won't be marked for garbage collection, but the rest of the object is still ready for garbage collection (assuming no one else is holding a reference to the component itself).
"When Angular sees a component is no longer needed in the DOM, it will destroy the component."
Basically, when the component isn't needed, ngDestroy() is called.
In this isntance, you can actually test to see if the component gets destroyed by implementing the lifecycle hook on the component, making the call to as you do above and then moving to a new view where the component isn't in the DOM.
The component should be destroyed just fine.