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

Is there a way to create a TypeScript function that can accept both mutable and immutable arrays as arguments?

Writing the following method became quite complicated for me. The challenge arose because any method receiving the result from catchUndefinedList now needs to handle both mutable and immutable arrays. Could someone offer some assistance? /** * Catch any ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

The QueryParams/ParamMap consistently returns as blank

Seeking assistance with retrieving a parameter called serverId from the URL. I have the following code setup: constructor(private peopleService: PeopleService, private route: ActivatedRoute) { this.route.paramMap.subscribe(params => { ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

The getAuth() helper found in the api directory's Clerk retrieves the following data: { userId: null }

I'm completely stuck here.. Currently working with the clerk and I am looking to access the userId of the current user using the getAuth() helper. For more information, refer to the docs: pages/api/example.ts import { getAuth } from "@clerk/n ...

Unveiling the Ultimate Method to Package Angular 2 Application using SystemJS and SystemJS-Builder

I'm currently in the process of developing an application and I am faced with a challenge of optimizing the performance of Angular 2 by improving the loading speed of all the scripts. However, I have encountered an error that is hindering my progress: ...

Update the AngularJS (1.5) application to Angular 5

Looking for advice on transitioning an AngularJS app to Angular (in this case, version 5). I've been exploring the official documentation, but I still have some uncertainties. From what I gathered in the guide, it suggests migrating from AngularJS by ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Getting started with accessing an API using Angular 2

I am seeking a way to navigate outside of my Angular 2 application to mywebsite.com/api. This link should direct me to an API application hosted on the same server. Here is my current route configuration. export const routes: Routes = [ {path: '& ...

The karma test appears as "passed" in IntelliJ, even though there are remaining errors present, leading to a failure in the CI/CD process

Currently working on an Angular project, my goal is to ensure all tests turn green. Surprisingly, they all passed on my end, but the CI/CD process (Teamcity) failed. Upon checking the log in my IntelliJ IDE, it was revealed that certain tests actually repo ...

What is the best way to incorporate Typescript React Components across various projects?

I'm venturing into developing an npm package that involves several react components implemented with typescript. As a newcomer to react and npm, I apologize if my query seems basic. Despite researching online, there isn't much information on this ...

Refreshing the private route redirects the user to the login page

Currently, I am working on setting up a private route within my React app. I have integrated Redux and Redux-Toolkit (RTK) Query for handling state management and data fetching. The issue I am facing is that whenever I reload the private page, it redirects ...

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

Angular's CanActivate feature fails to navigate to a new route upon calling the refresh token API, even if it returns true

I have been implementing route guard and token interceptor in an Angular 6 project. Within the route-guard's canActivate method, there is an async function that verifies whether the access token has expired: If it has expired, the system checks i ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

What could be causing maven install to throw an error in relation to npm?

After merging two branches, an error occurred: [ERROR] The goal com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm) on project frontend failed to execute because it couldn't extract the npm archive located at & ...

The @Hostlistener method consistently returns an 'undefined' value when passing in the @Input() value

I'm encountering an issue where the value from @Input() is undefined in my @Hostlistener method. What could be causing this? export class InputHelpComponent implements OnInit { isOpened: boolean = false; @Input() field!: string; @HostListener(& ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...