Throughout my experience with various Angular projects, I have encountered the challenge of effectively sharing application-level data between different pages.
There are several methods to tackle this issue, such as using a service and injecting it into pages that require the same data. I have also come across projects that utilize local storage to persist common data for easy retrieval by other pages.
Lately, I implemented a solution that I found to be more efficient: I introduced a base page with an injected data service to facilitate data sharing among subclasses. By injecting the service at the base class level only, I eliminated the need to inject it in every single page. To achieve this, I stored a reference in a static data member within the base class. If the injected data service is present in the constructor, I save it to the static member. If not, I initialize the class instance with the value from the static data member. This approach allows me to access the injected data in the base class and its subclasses seamlessly.
Below are snippets of the sample code:
// Omitted for brevity
@Component({
selector: 'base-page',
templateUrl: "./index.html",
styleUrls: [ "./index.scss" ],
})
export class BasePage implements OnInit {
static dataService: DataService;
constructor(public dataService?: DataService) {
console.log("dataService", dataService);
if (dataService) {
console.log("Data service is set in the BasePage");
BasePage.dataService = dataService;
}
else {
this.dataService = BasePage.dataService;
}
}
ngOnInit() {
console.log("Hello BasePage");
}
}
// Omitted for brevity
@Component({
selector: 'home-page',
templateUrl: "./index.html",
styleUrls: [ "./index.scss" ],
})
export class HomePage extends BasePage implements OnInit {
constructor() {
super();
}
ngOnInit() {
console.log("Hello HomePage");
console.log("Data", this.dataService.appLevelData);
}
}
Have you experimented with a similar approach? How do you prefer sharing common data across pages in your applications?
I look forward to hearing your input, as I believe diverse perspectives on this matter can greatly benefit other developers as well.
Thank you in advance.