Efficient ways to exchange data at the application level across pages in Angular 2 and higher versions

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.

Answer №1

Typically, I prefer to integrate the services within the constructors, however, I understand your perspective. I am open to experimenting with a new approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The user interface is not being refreshed in the select box after removing control from the reactive form

Within my project, I am utilizing "@angular/cli": "1.2.6", "@angular/core": "^4.0.0" Objective My goal is to create a dynamic form for a product that includes feature inputs. When the user clicks the "add feature" button, a new feature column with a sel ...

Dexie is alerting us to a problem with a call that occurs before initialization

When setting up my application, I encountered an error related to the Courses Entity Class being called before initialization in my Dexie Database. Despite checking my code, I couldn't find any issues and there was no documentation available for this ...

Using boolean value as default input value in React

When trying to set the default value of a controlled checkbox input from my request, I encountered an error stating "Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'". Do you have any suggestion ...

Updating row values in an Angular table

I have a reusable table with the [cellData]="row" attribute to populate each cell on the table (see sample table in the screenshot). My question is, how can we replace the null values on the template with "---" so that instead of displ ...

Expanding a JSON type in Typescript to accommodate interfaces

Expanding on discussions about passing interfaces to functions expecting JSON types in Typescript, this question delves into the complexities surrounding JSON TypeScript type. The scenario involves a JSONValue type that encompasses various data types like ...

Utilizing Agora's Screenshare Feature with Angular 8

I am currently working on integrating Agora into my Angular 8 application. So far, I have been able to successfully join and leave video calls. However, I am facing challenges with integrating screen sharing functionality. According to the Agora official d ...

Angular's Motion Module

Incorporating Angular-5 into my project has introduced a plethora of animations on various pages. While the utilization of jQuery provides a straightforward approach for adding and removing classes to DOM elements, it is frequently advised against using jQ ...

Struggling to import a React component for sharing purposes

I've developed a React component that I want to share through a locally hosted npm repository. To achieve this, I created the React component using typescript, transpiled it to JavaScript, and then published the resulting code to the repository. Howe ...

Exploring Reactive Programming with RxJS and organizing data into individual streams

As I delve deeper into working reactively with Angular 15 and RxJS observables for a UI component, my focus lies on subscribing to data solely within the component template (html). The data is fetched from an external system through a service. However, a c ...

Exploring the automatic type inference functionality of Typescript for generic classes

Although it may seem simple, I am struggling to pinpoint the cause of this error. I have been searching for a solution for quite some time, but I have yet to find one. class MyClass<T > { property: T = 5 // Error Here: Type '5' is not as ...

Can I use http.get() on Stackblitz to fetch a JSON data file?

One of my Angular services is structured as follows: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

`A bug in my Angular 4 application causes a TypeError when hosted on IIS`

After hosting an Angular 4 app on IIS, it seems there is an issue when accessing the app from machines other than the ones used for development. An error message " 'Uncaught TypeError: undefined is not a function' common.es5.js:3084" appears on t ...

The stack property of [object Object] cannot be updated, as it only has a getter method

I can't figure out why I'm receiving this specific error in the Plunker below. Cannot set property stack of [object Object] which has only a getter Access the Plunker here: https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview The code causi ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Webpack and incorporating bespoke scripts

Can someone please help me understand how webpack works? I'm currently working on an Angular 2 project with a webpack starter and I have some JavaScript scripts from AWS (my SDK for API Gateway). These are about 10 JS files that I currently have liste ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

The integration of Angular CLI with SCSS is no longer a separate process -

It seems like I might be overlooking something very straightforward here. After a fresh installation of angular-cli, I created a new website with SCSS. I input the SCSS in the global style.scss as well as some in a component SCSS file. However, when I se ...