Transmit diverse data to a different (unassociated) module within Angular

I am struggling to pass the content of a variable from one component to another in Angular. The two components are on different pages and not directly related, but I need to access the value of the variable in the second component's TypeScript file without displaying it on any page. Despite trying various tutorials, I have not been successful and feel lost about how to proceed.

Here is the file layout (I need to transfer variable content from the week component to the day component)

The code snippet below is located in p1_week-chart.component.ts:

else if (chart.data.labels[activeEls[0].index] == "Wednesday") {
          this.dayClicked = new Date(this.today);
          this.dayClicked.setDate(this.dayClicked.getDate() + 2);
          console.log(this.dayClicked);
          //seeking to send the content of this.dayClicked to the other component (p1_day-chart.component.ts)

Extra information: I only require TypeScript for this scenario, no HTML elements needed.

Any assistance would be greatly valued!

(Despite experimenting with several solutions such as BehaviorSubject, I am unable to successfully transmit the content of this.dayClicked to the p1_day-chart.component.ts file. While I've seen similar queries raised here, none of the suggestions have resolved my issue.)

Answer №1

When working with unrelated components, a straightforward method to achieve your desired outcome is by passing the variable from one component to another through emission. To do this, you can utilize a service like the following:

import { Injectable, EventEmitter } from '@angular/core';
import { Subscription } from 'rxjs/internal/Subscription';

@Injectable({
  providedIn: 'root'
})
export class DataTransferService {

  emitData = new EventEmitter();
  subscription: Subscription;

  constructor() { }

  sendUpdatedData(key, value) {
    var dataToEmit = [key, value];
    this.emitData.emit(dataToEmit);
  }
}

In the component where you are emitting the variable:

  • Import DataTransferService
  • Declare private dataTransfer: DataTransferService in the constructor Then, when you have the variable ready to be emitted, use the following code:

this.dataTransfer.sendUpdatedData("Item selected", this.selectedItem);

In the component that needs to receive the variable:

  • Import DataTransferService
  • Declare private dataTransfer: DataTransferService in the constructor

this.dataTransfer.subscription = this.dataTransfer.emitData.subscribe((emittedData) => { if (emittedData[0] == "Item selected") { this.receivedSelectedItem = emittedData[1]; } });

Answer №2

Rephrased based on your input @s_frix,

The component that requires the variable currently has this setup:

import { SharedParamsService } from 'src/app/components/charts/testcomponent';

//Some irrelevant code has been omitted here

//if dayClickedReceived: any; is added and console logged in ngOnInit() it will show "undefined"

  constructor(private http : HttpClient,
    private globalvars: GlobalvarsService, //not important
           private adapter: DateAdapter<any>, //not important 
    private datePipe: DatePipe, //not important
  private sharedParams: SharedParamsService) { console.log(this.urlDate); }
//ignore the console log that's for something else
              
  ngOnInit(): void {
  this.sharedParams.subsVar = this.sharedParams.invokeFirstComponentFunction .subscribe((emitted) => { if (emitted[0] == "Day clicked") { this.dayClickedReceived = emitted[1]; } });
}

Encountering error: "Property 'dayClickedReceived' does not exist..." If I create it and log it later, it shows as "undefined" when I switch to the page requiring it. (The event logs correctly when sent, but remains undefined when needed on the other page)

The goal is for the variable to be sent and triggered on the sending page, then accessed and utilized on the receiving page

Answer №3

I managed to make it work using the following method:

//Service:
import { Injectable, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SharedParamsService {

  message: string
  
  constructor() { }
  
  setMessage(data) {
    this.message = data;
  }

  getMessage() {
    return this.message;
  }

}

//Sending component:
message: any;

constructor(private sharedParams: SharedParamsService){}

//When the action occurs and a variable needs to be sent
this.sharedParams.setMessage(this.dayClicked);


//Receiving component:
message: any;

constructor(private sharedParams: SharedParamsService){}

ngOnInit(): void {
    this.message = this.sharedParams.getMessage(); 
}
//Now 'this.message' holds the correct variable that was sent and can be used in this component later on.

Big thanks to everyone for sharing their answers, really grateful! :)

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

Encounter the error message "Unable to resolve all parameters" after including the Interceptor

Currently, I am in the process of implementing HttpInterceptor functionality. However, upon adding it to @NgModule, I encountered the following error message in Chrome: Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?). at s ...

Discover one among numerous interfaces available for handling Promise responses

My API handler returns a promise of a type. The object returned can be one of the following interfaces, depending on the API response: export interface Event { statusCode: number } export interface CreateEvent extends Event { data: Object } export in ...

What is the most efficient way to organize a JSON by a designated property in order to showcase it in an Angular data table?

Hello, I have a question. I need to organize the JSON data obtained from an API before displaying it in a datatable. My goal is to sort the data by a specific property just before passing it to the datatable for direct display. Below is the code I use to ...

Hiding collapsible navbar in Angular 7 when in responsive mode

Hey there, I'm currently using a navbar in Angular 7 and I'm looking for a way to collapse it when clicking on another area of the page. When resizing my browser or when accessing the app on mobile, the navbar displays a menu icon with three bars ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

The name '__DEV__' is not discoverable at the moment

While working with the mobx library in my project, I encountered an issue after installing it using npm. Upon exploring the mobx/src/error.ts file within the node_modules folder, I came across a compile time error on line 78: const errors: typeof niceError ...

Exploring the capabilities of Angular and Django Rest Framework applications

Imagine having a front-end application built in React and a back-end application developed using Node.js with Express. The back end has been thoroughly tested with Mocha, and now it's time to create functional tests for the front end. However, since t ...

Is it possible to utilize a template literal with a variable as an object key?

I tried to run the following code snippet but encountered an unexpected error: interface Person { firstName: string } const property: 'Name' = 'Name' const zack: Person = { [`first${property}`]: 'Zack' } An error is th ...

Issue with TypeScript when using Redux DevTools Extension: "Type 'Window' does not contain property '__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'."

Encountering an issue in my index.tsx file. Getting the error message: "Property 'REDUX_DEVTOOLS_EXTENSION_COMPOSE' does not exist on type 'Window'." Below is a snippet of my index.tsx code: import * as React from 'react'; ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

Troubleshooting problem with applying ngClass to rows and columns in ngFor

Working with Angular2 and its ngFor feature, I aim to differentiate odd and even rows visually by applying different colors to them. Here's the code snippet I tried (but it didn't quite work as expected): <div *ngFor="#meeting of meetingList ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Tips for declaring a dynamically sized array in Typescript?

Is there a way to create an array structure where the first element is always a number and the following elements are always strings, with a minimum length of 1? This is my current approach: type MyArray = | [number] | [number, string] | [number, s ...

ability to utilize controller object through service

Here is the code for my controller : constructor(Auth, $http, $rootScope, $log, $scope, $uibModal, loginTemplate, demandCity, signupTemplate, socket) { this.isLoggedIn = Auth.isLoggedIn; this.$http = $http; this.socket = socket; this.awesomeDemand ...

Troubleshooting a cross-component property problem involving a fetch request within a subscription

My current objective is to utilize ActivatedRoute parameters to make a fetch request and update a class property with the fetched data. Progress has been made on making the request, but I am facing difficulties in getting the fetched data to the specific c ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

Limiting the input of a user to a maximum of a five-digit integer with a maximum of two decimal points using Angular 2 and ngModel

Currently, I am working on an input text field that utilizes [(ngModel)]. My goal is to restrict users to entering only a maximum of 5 digits with up to 2 decimal places. I believe creating a directive is the best approach to achieve this, however, I am un ...

How can one access the request context from within a decorator in Nest JS?

I am developing a custom decorator to capture request information export const Tracking = () => { return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => { const method = descriptor.value; descriptor.value = async funct ...

Is it possible to verify if an object matches a type without explicitly setting it as that type?

In order to illustrate my point, I believe the most effective method would be to provide a code snippet: type ObjectType = { [property: string]: any } const exampleObject: ObjectType = { key1: 1, key2: 'sample' } type ExampleType = typeof ...

React.jsx: The type provided is invalid; it should be a string for built-in components or a class/function, but instead, an object or react-native-ui-datepicker was received

I am facing an issue with a component that utilizes the DateTimePicker tool from the react-native-ui-datepicker library. When I try to write a test case for it using jest, an error is being displayed: Warning: React.jsx: type is invalid -- expected a str ...