`Sharing data between multiple Angular components using a service is not functioning properly`

This is a sharing service called dShareService:

@Injectable()
export class DInfoShareService {
    constructor() { }

    // Observable sources    
    private dInfo = new Subject<DInfo>();

    dInfo$ = this.dInfo.asObservable();

    // Service message commands
  public SetDInfo(dinfo: DInfo) {     
    this.dInfo.next(dinfo);
  }
}

This is the parent component:

Within the parent component, there is a button click event that triggers a method which passes data to a service.

GoToDetail(value){       
    this.dShareService.SetDInfo(value);

    // This is a child component and is accessed via a route. Typically, I would use the current state and pass data to the child 
    // component. However, in this scenario, there are 3 tab pages on the UI and each page requires this data.
   
 this.router.navigateByUrl('/dchild', {
          state: {dInfo: value}
    });

This is the child component:

Within the constructor,

this.dinfoShareService.dInfo$.subscribe(res=>
     {
       //This part never gets executed
       this.dInfo = res;
     } 
  );

The subscription within the child component is not triggering. Can anyone help me identify what I am doing wrong?

Answer №1

Give this a shot, We can start by updating the Service.ts file

import { BehaviorSubject, Observable, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiWalletService {
  private behaviorSubject = new BehaviorSubject<Object>('');

  setBehaviorView(data: object) {
    this.behaviorSubject.next(data);
  }

  /** Retrieve Behavior for user registration */
  getBehaviorView(): Observable<object> {
    return this.behaviorSubject.asObservable();
  }

}

In component1.ts

 {
     ngOnInit() {
            this.setBehaviorView({
              'data':'XYZ'
            })
       }
    }

In component2.ts

{

 constructor(private service: YourService){}

 ngOnInit() {
 this.service.getBehaviorView().subscribe(async (data) => {
   if (data && data != undefined) {
      console.log(data)
    }
  })
}
}

Answer №2

Your implementation of the Subject in your service seems to be incorrect:

@Injectable()
export class DInfoShareService {
    constructor() { }

    // Observable sources    
    private dInfo = new Subject<DInfo>();


    // Service message commands
  public SetDInfo(dinfo: DInfo) {     
    this.dInfo.next(dinfo);
  }
}

It should not be called inside the constructor, instead use it inside the ngOninit method.

     ngOnInit(): void {

this.dinfoShareService.dInfo.subscribe(res=>
     {
       //this one never happen
       this.dInfo = res;
     } 
  );

});

Answer №3

For your decorator to be singleton across components, you should modify it to

@Injectable({ providedIn: 'root' })
. Otherwise, it will create multiple instances for different components.

Another thing to consider is:

GoToDetail(value){       
    this.dShareService.SetDInfo(value);   
    this.router.navigateByUrl('/dchild', {
          state: {dInfo: value}
    });
}

In the above code snippet, the SetDInfo method is called before navigation takes place. This means that your child component may not receive the updated value in time. To address this issue, change your Subject to a BehaviorSubject so that the last set value can be accessed.

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 are my values not being applied to the model class in Angular 7?

I'm currently developing an online shopping website where I have defined my order Model class as shown below: import { User } from './user.model'; export class Order { constructor(){} amount: Number = 0; status: String = ""; date: ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...

Unable to initiate ng-click event in AngularJS

Looking to trigger a function in TypeScript from the view using AngularJS. My technology stack includes AngularJS, TypeScript, and ASP.Net MVC3. Here is the link in the UI: <div id="left_aside" ng-controller="MyGivingPortfolioController"> <div ...

Empty dialog box displayed in production for Angular material datepicker

I'm facing an issue that I can't seem to figure out. The code works perfectly fine when I run it locally using ng build and ng serve. However, when I moved it to production, it started misbehaving. When I tried to replicate the issue in my local ...

Encountering an Invalid JSON error on the Developer console

I'm in the process of building a React application and aiming to establish a connection with my Back4App database. Within the Back4App dashboard, there exists a Person class containing data that needs to be retrieved. It appears that the call is being ...

Unlocking the Power of Angular 12: Leveraging the Subscribe Method to Access Multiple REST APIs

We have a task where we need to make multiple REST API calls from the ngOnInit() method, one after the other. After making the first call, we need to pass the response to the second API call, and similarly for the third call, we need to get the value from ...

Do not trigger subscription after debounce time in Angular

I would like the input data to be emitted after 300 milliseconds using debounceTime in Angular: subject: Subject<any> = new Subject(); constructor(private formBuilder: FormBuilder) { } ngOnInit(); sendValue(): void { this.subject.pipe(debounceTim ...

What is the best approach to utilize the GET method in Angular 2 to call a SOAP API

I recently completed a project in Angular 2 and now I am looking to call a SOAP API using the GET method in Angular 2. While I have experience using SOAP in AngularJS 1 and found the packages quite easy to use, I have not been able to locate any packages ...

Displaying percentage values within the chart in ng2-chart: A simple guide

I have been researching for hours but cannot find the solution to my issue. I am utilizing ng2-chart to create charts on my dashboard. The charts are functioning correctly, but my problem lies in displaying percentage values within the doughnut chart. Thi ...

The kendo-chart-tooltip script is causing an error by generating an Uncaught TypeError: background.isDark is not a recognized function

Click here for image descriptionHaving issues with the kendo-chart-tooltip functionality in my Angular 5 platform. The console shows a script error related to 'background.isDark' not being a function. zone.js:192 Uncaught TypeError: back ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

What is the process for bringing in AngularJS 2? // Bring in { routerTransition } from './router.module;

Currently, I'm experimenting with implementing page transitions using Angular 2. The resources I've gone through indicate that I need to import: // import { routerTransition } from './router.module; However, despite following these instruc ...

Invoke a public method in TypeScript

I'm a newcomer to typescript. In my node-express application, I am trying to call a public function. However, I keep encountering an issue where this is always undefined, leading to errors whenever I attempt to call the public function. Below is the s ...

What is the process for sending a post request in Ionic 2 to a Node server running on localhost?

When working with Ionic, I utilized a service provider to access HTTP resources. The Service.ts file looks something like this. Here, data is represented as a JSON object. import { Injectable } from '@angular/core'; import { Http, Headers } fro ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Error message: WebStorm shows that the argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type<any> | "root" | null} and InjectableProvider

Transitioning my app from Angular v5 to v6 has presented me with a TypeScript error when trying to define providedIn in my providers. The argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type | "root" | null} & ...

Troubleshooting Issues with Imports in Jest and Typescript

I am currently facing issues with my Jest, Enzyme, and Typescript setup where some imports are showing up as undefined. One example is the import statement import ReactMarkdown from 'react-markdown'; in one of my files. Whenever I run the tests, ...

working with JSON arrays in angular framework

Is there a way to print a specific value from an array in typescript? Below is the code snippet in typescript that I'm working with: import { AngularFirestore } from '@angular/fire/firestore'; export class ProfileComponent implements OnInit ...

Is it possible to combine various SVG icons into a single component?

I am currently able to code SVGs in React-Native using typescript. This allows me to call them as individual react native components. Below is an example of my current capability: <View> <BackArrow color ="red" wid ...

Responsive Container MUI containing a grid

I am attempting to replicate the functionality seen on YouTube's website, where they dynamically adjust the grid layout based on the container size when a Drawer is opened or closed. Essentially, it seems that YT adjusts the grid count based on the c ...