Ways to utilize Subjects for sharing global information in Angular 6

I have been struggling to find an effective way to share data between two components that have the same parent in an Angular application.

Currently, I am working with an Angular Material stepper where Step 1 contains one component and Step 2 contains another component. My goal is to trigger an action by clicking a button in the Step 1 component that will update an array of data used by the Step 2 component.

Here is a snippet of my code:

Global service:

export class GlobalDataService {
  private dataSubject = new BehaviorSubject<any[]>([]);

  currentData = this.dataSubject.asObservable();

  constructor() { }

  changeData(newData: any[]) {
    this.dataSubject.next(newData);
  }
}

Component 1 responsible for updating the data:

updateData(id) {
  this.apiObservableService
    .getService('http://localhost:8080/Spaces/' + id)
    .subscribe(
      result => {
        this.space = result;
        this.globaldataservice.changeData(result.reserves);
        sessionStorage.setItem('currentSpace', JSON.stringify(result));
      },
      error => console.log(error)
    );

}

Component 2 which reads and refreshes the data:

ngOnInit(): void {

    this.currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
    this.currentSpace = JSON.parse(sessionStorage.getItem('currentSpace'));

    this.globaldataservice.currentData.subscribe(data => this.reserves = data)
    console.log(this.reserves);
}

Answer №1

Overall, your code seems to be functioning well, but I have some additional tips on how to handle it effectively.

In addition, GlobalDataStore should provide the BehaviourSubject as an Observable, allowing for subscription.

It is also advisable to keep behavioursubject private.

export class GlobalDataService {
  private source = new BehaviorSubject<any[]>([]);

  get source() {
       return this.source.asObservable();
  }
}

Then, simply subscribe to it within the component.

Furthermore, I typically implement these methods in my stores (given my use of BehaviourSubject)

//Obtains the most recent value pushed to the BehaviourSubject
get sourceLastValue() {
   return this.source.getValue();
}

//Creates a deep copy of the latest value for precise form editing
get sourceForEdit() {
    return __lodash.cloneDeep( this.source.getValue() );
}

PRO PERFORMANCE TIP!

Lastly, it is crucial to unsubscribe from observables to prevent them from remaining active indefinitely, even after the component is destroyed. Additionally, by initializing the observable in ngOnInit, a new subscription is created each time you navigate to and from the component.

For more information on how to properly unsubscribe from subscriptions in components, please refer to this article.

Angular/RxJs When should I unsubscribe from `Subscription`

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

Why is the CanDeactivate Guard unable to access a function within my component?

My routes are being loaded lazily and I am facing an issue with the CanDeactivate guard not being able to access the component's properties or methods as required by the documentation. Below is the implementation of my guard: @Injectable() export cl ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

Developing a MEAN-based calendar application that is constantly monitoring for updates

I am considering developing a calendar web app to enhance my web development skills. After carefully planning the structure and technologies, I have decided to use the MEAN stack. However, I have encountered a challenge: I want the angular front-end to a ...

Exploring ViewChild Usage in Angular 8's Inheritance

I've encountered an issue with inheritance and ViewChild in a class where I always seem to get undefined. Let me simplify the problem for better understanding. First, let's look at the parent class: @Component({ selector: 'parent', ...

Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is restricted to binding with Iterables like Arrays. Unfortunately, there is no current solution available for this issue

I'm encountering a minor issue with my code. I have two HTTP requests and after combining the data from both, I encounter an error when trying to loop through the final array. I've read other posts suggesting that the returned object is not an a ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

Typescript error points out that the property is not present on the specified type

Note! The issue has been somewhat resolved by using "theme: any" in the code below, but I am seeking a more effective solution. My front-end setup consists of React (v17.0.2) with material-ui (v5.0.0), and I keep encountering this error: The 'palet ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

The name 'Firebase' is not recognized by Typescript

Encountering typescript errors while building a project that incorporates angularfire2 and firebase. Here are the packages: "angularfire2": "^2.0.0-beta.0", "firebase": "^2.4.2", Listed below are the errors: [10:58:34] Finished 'build.html_css&apos ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

ng-deep is causing changes in sibling components

Facing a challenge with Angular Material Design as I discovered the need to utilize ng-deep to customize the styling of an accordion. The issue is that when I use this method, it affects another accordion in a different section which is undesirable. Is th ...

What is the best way to incorporate audio playback while browsing files on an HTML5 webpage with TypeScript?

<input type="file" id="soundUrl" (change)="onAudioPlay()" /> <audio id="sound" controls></audio> This is the HTML code I'm working with, and I'm looking to trigger audio playback after a user selects an MP3 file using TypeScrip ...

Struggling to locate components in your React, Next.JS, and Typescript project? Storybook is having trouble finding them

I have set up Storybook with my Next.js, TypeScript, and React project. The main project renders fine, but Storybook is breaking and giving me the error message: "Module not found: Error: Can't resolve 'components/atoms' in...". It appears t ...

Exploring the use of national flag emojis in VS code

I've been attempting to use flag emojis as reactions on a Discord bot, but they just won't cooperate. Every time I try something like this > ':flag_jp:', I encounter the following error: Error: DiscordAPIError: Unknown Emoji EDIT ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

When trying to install Angular 6 locally, I encountered an issue with Angular 10 where the package.json file was being ignored

Recently, I encountered an issue with my Angular project. I have a project based on Angular 6.0.7 which I pulled from our repository. On a global level, I have Angular 10.0.4 installed. Despite having the correct version specified in my package.json file, ...

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

Is it possible to constrain generic indexed access parameters?

Consider the following scenario: type Group = | { type: "string"; payload: string; } | { type: "number"; payload: number; }; A function can be created as shown below: const groupFunction = <T exte ...

Step-by-step guide to designing a basic pagination/carousel using div elements in HTML and Angular 2

Hey there! I'm currently working on a project with an *ngFor in my template that generates multiple divs. <div *ngFor="let item of widgets" class="page-content widget-item"> <div>{{content}} </div> </div> I'd like to i ...

What is the best way to utilize scope apply or run functions upon successful completion in Angular 8 jQuery ajax requests?

Due to reasons that I won't delve into here, I have opted to use jQuery ajax instead of Angular's http. This means I am making an ajax call to my php server. However, a problem arises where any code within the success/error blocks is confined to ...