Sharing data between different Angular components that are not directly related can be achieved by utilizing a service in Angular

This is the service class for managing data

export class DataService {
  public confirmationStatus = new Subject();

  updateConfirmationStatus(status: boolean) {
    this.confirmationStatus.next(status);
  }

  getConfirmationStatus(): Observable<any> {
    return this.confirmationStatus.asObservable();
  }

}

This is my first component

 constructor(   
    private dataService: DataService
  ) 
confirmationStatus: boolean = true;

 leave() {
   this.dataService.updateConfirmationStatus(this.Confirm);
 }

This is another component where leave() is triggered by a click event in html.

 confirmation: boolean;
    checkExit(): boolean{
     subscription: Subscription;
     this.subscription = this.dataService.getConfirmationStatus().subscribe((status) => {
          console.log(status);
          this.confirmation = status;
          console.log(this.confirmation);
        });
    }

This is the route guard implementation

export class DeactivateGuardService implements CanDeactivate<SolutionCanvasComponent> {

  component: Object;
  route: ActivatedRouteSnapshot;

  constructor() { }

  canDeactivate(component: Component2,
                route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot,
                nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return component.checkExit();
  }

I'm facing challenges in passing data from the first component to the second component. Should I include the service in the providers array of any module?

Answer №1

Make sure to properly register the observable before triggering the event:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ConfirmationService {
  public confirmationSubject = new Subject();
  public confirmationObservable$: Observable<any>;

  constructor() {
    this.confirmationObservable$ = this.confirmationSubject.asObservable();
  }

  sendConfirmation(isConfirmed: boolean) {
    this.confirmationSubject.next(isConfirmed);
  }

  getConfirmation(): Observable<any> {
    return this.confirmationObservable$;
  }
}

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

Uploading an Image to a SharePoint Group Folder using an Angular Application

I have a project in which I am developing an app using Angular to upload images to a SharePoint site. Specifically, I want to upload images from the Angular app to a private folder within a SharePoint group. I am utilizing Microsoft Graph API and Azure AD ...

After the initial test is executed, Jasmine's spy-on function proceeds to call the actual function

The issue arises when the second test fails due to an error message stating that "Cannot read property 'get' of undefined". This error occurs because the second test references the real service, which contains a private property called "http" tha ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Is it advisable to deactivate change detection during the initialization phase of an Angular app?

Just to provide some background: My Angular 5 application goes through a startup cycle that involves: HTTP calls to server APIs (checking token, retrieving user data) Local storage (database) calls A significant initialization process to prepare and tra ...

The Nestje subscription is encountering a NULL value and displaying an error message stating: "Non-nullable field Subscription cannot be returned as null."

I attempted to implement a Subscription in my nestjs project with GraphQL, but encountered the following error message: Cannot return null for non-nullable field Subscription Below is the code snippet: //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~ ...

Issue with Angular/HTTP POST request where boolean data is being passed as blank

I've been encountering an issue while trying to send data to an API - specifically, my boolean data is not being transmitted correctly and shows up as blank. I'm curious if anyone has any insights on what might be causing this problem? const noti ...

Using CamanJs in conjunction with Angular 6

Struggling to integrate camanjs with Angular 6? Wondering how to add the JavaScript library and use it within an Angular project when there are no types available on npm? Here are the steps I followed: First, install Caman using npm. Next, add it to ...

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal() { fetch('https://kyoala ...

Is it possible for Typescript and Next.js to import a different project's *source code* only from the module's root directory?

Issue with Sharing React Components between Closed and Open Source Next.js Projects I am facing a challenge in my development setup involving two Next.js projects, one closed source (Project A) and the other open source (Project B). In Project A, which is ...

How can interfaces be effectively integrated with node and mongoose?

I am working on a model interface where I need to fetch specific data from the record // file: code.interface.ts import { Document } from 'mongoose'; export interface CodeI extends Document { readonly _id: string; readonly logs: any; } Howe ...

The dropdown navigation bar fails to close upon being clicked

I'm currently facing an issue with the navbar in my project. The bootstrap navbar doesn't close automatically after clicking on a link. I have to move my mouse away from the navbar for it to close, which is not ideal. Additionally, I'm worki ...

Tips for creating a tailored Express.js request interface using Typescript efficiently

I have been working on designing a custom Express request interface for my API. To achieve this, I created a custom interface named AuthRequest, which extends Request from Express. However, when attempting to import my interface and define req to utilize t ...

Sluggish website loading time

Hey there, I'm currently developing a website and I'm facing a major issue with one of my pages loading slowly and experiencing lag. I'm unsure if this is due to the on scroll listeners or the excessive references in my code. Could it possib ...

Utilizing a string as an index in TypeScript

Struggling with the following code snippet: interface IStudentType { [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics } The error message received is TS1268: An index signature parameter type must be 'string', &apos ...

Memory Leak in Angular's Chain of mergeMap and concatMap Functions

I am facing an issue where a memory leak is being caused for each processed file during the upload of a 1 TB folder to Blob Storage. I have implemented a parallel processing pipeline using mergeMap to handle the files through a series of steps with concatM ...

Long loading times observed for larger datasets in Angular4 Datatable

I am currently experiencing slow loading times for my datatable when trying to display the data. The script is being called within the component like so: ngAfterViewInit() { $.getScript('./assets/js/datatables/datatable-basic.js'); } T ...

Placing a blank object after every line within a TypeScript array

I'm currently working on creating an iterator using the .map() function, specifically in this way: const csv = this.invoices .map(data => ({ invoiceId: data.invoiceId, invoiceDate: data.invoiceDate, invoiceType: data.invoiceType, ...

To set up Ionic on your project, run the command `npm install

After setting up a new Ionic project, I included the Android platform using the command ionic cordova platform add android. This action added the following entry in the config.xml file: <engine name="android" spec="~6.1.2" /> Prior to this, I came ...

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...