Reputation: 2977
Is actually possible to do something like this?
import {Injectable} from '@angular/core';
@Injectable()
export class UbiSharedService {
private _ubiData: object = {};
private $$instance: UbiSharedService;
constructor() {
}
public setData(key: string, data: any) {
this._ubiData[key] = data;
}
public getData(key: string): any {
return this._ubiData[key];
}
public popData(key: string): any {
return delete this._ubiData[key];
}
public getInstance(): UbiSharedService {
if (!!this.$$instance && this.$$instance instanceof UbiSharedService) {
//NOOP
}
else {
this.$$instance = new UbiSharedService();
}
return this.$$instance;
}
}
Upvotes: 0
Views: 631
Reputation: 2088
Please see the following documentation from Angular to learn how to use services to share data between unrelated components: https://angular.io/guide/singleton-services.
You can inject services in components by adding them to the constructor of the component:
constructor(
private ubiSharedService: UbiSharedService
) {
// You can now call in the methods of ubiSharedService
// e.g.: this.ubiSharedService.setData('key', { value: 'Value' });
}
Upvotes: 1
Reputation: 60538
Get rid of the $$instance
and instead inject the service into the components that need it using the constructor.
constructor(private productService: ProductService,
private productParameterService: ProductParameterService) { }
Then the component can access the service methods using the productService
or productParameterService
properties.
Upvotes: 3