I am encountering an issue with a shared service in angular. Upon application startup, the init function is triggered, fetching and returning data that is vital across the entire application.
Components have the ability to inject this service and retrieve the data; however, the data can be altered within the component as well. In my current setup, every modification made to the object within my component reflects on the object returned by the shared service.
@Injectable()
export class SharedDataService {
private _object1: SomeType[];
private _object2: SomeType[];
private _object3: SomeType[];
constructor(private _http: HttpClient, @Inject('BASE_URL') private _baseUrl: string) {}
public init() {
this._http.get<IInitModel>(this._baseUrl + 'init').subscribe(
(r: IInitModel) => {
this._object1 = r.object1;
this._object2 = r.object2;
this._object3 = r.object3;
}
}
public getObject1(){
return this._object1;
}
public getObject2(){
return this._object2;
}
public getObject3(){
return this._object3;
}
The init() function is executed during app startup to acquire essential data for the application. Within my components, I access this data like so:
export class SomeComponent {
public object1: SomeType[];
constructor(private _sharedDataService: SharedDataService) {}
ngOnInit() {
this.object1 = this._sharedDataService.getObject1();
}
}
If I make changes to the object in the ngOnInit method of my component
this.object1.push({ prop1: 1, prop2: "SomeValue" })
The private member's value in the shared service also gets altered.
console.log(this._object1) // Output from shared service: [{ prop1: 1, prop2: "SomeValue"}]
console.log(this.object1) // Output from component injecting the service: [{ prop1: 1, prop2: "SomeValue"}]
Is this behavior expected? Are objects passed by reference when returned as implemented in my service?
Could someone suggest a more efficient approach to address this scenario?