Passing Data Between Components in Angular Using a Service

One of my services involves setting an ID, with the ID itself being obtained from another component through a click event.

export class MyService {

   id: number;
   constructor() {}

   public setId(value: number) {
          this.id = value;
          console.log('id:', this.id);
   }
}

The process of setting the value occurs within a click event located in my menu component:

<a [routerLink]="['item.id]" (click)="getId(item.id);">

This click event triggers a method within the menu component:

getId(datavalue: number) 
      {
            this.ms.setId(datavalue);
      }

Now I need to pass this value to another component so that it can be displayed in HTML. How can this be achieved?

class MyComponent implements OnInit
{
   id: number;

   constructor(private ms: MyService)
    {
       this.id = ms.id;
       console.log('ms id = ', this.id);
    }

Even though I attempted the approach above, when checking the console log, the output shows "undefined".

Answer №1

Note: Please avoid using an EventEmitter in a Service, consider alternative solutions! For a comprehensive discussion on this topic, refer to: Delegation: EventEmitter vs Observable in Angular

A common approach is utilizing an EventEmitter in the Service:

id: number;
  idUpdated = new EventEmitter();

  setId(value: number) 
  {
         this.id = value;
         this.idUpdated.emit(this.id);
         console.log('id:', this.id);
  }

  getId() {
    return this.id;
  }

To monitor property changes in your detail component, you can subscribe to them:

id: number;
ngOnInit()
   {
    this.ms.idUpdated.subscribe(
        (id) => {
          this.id = this.ms.getId();
          console.log(this.id);
        }
      );
   }

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

What steps can be taken to resolve the Typescript errors related to the window object in my Vue application?

Within my Vue 3 app component, I need to interact with custom properties on the Window object, as shown below: window.ZohoHCAsapSettings = { //<-- ERROR HERE ticketsSettings: { preFillFields: { email: { defaultValue: user.value?.emai ...

I am currently working on integrating a Material Sorted feature

I am currently working on implementing Material Sorting, with the help of this reference: https://material.angular.io/components/sort/overview An interesting twist in my implementation is that I load my data after making a selection from a dropdown contro ...

Using the spread operator with objects in TypeScript: a beginner's guide

Currently, I am retrieving data from Firestore: getDocs(colRef).then( (val) => { const tempArray: Array<categoryFetchData> = val.docs.map((d) => { const categoryData: {categoryName: string, color: string, createdAt: Timestamp} = d.d ...

What are the steps to resolving a version error in angular cli?

I need help resolving the error related to the Angular version I am encountering. Can anyone provide guidance on how to fix this issue?The image above displays the current ng cli version and the specific error message I am facing. ...

How to pass an object between two Angular 2 components without a direct connection

My application is structured in the following way. <app> <header> <component-a></component-a> </header> <div> <router-outlet></router-outlet> <component-b></component-b> ...

The document reference is not valid. It must have an equal number of segments, but the reference cities/SF/landmarks has 3 segments

Hello! I am currently learning from the firestore tutorial Initially, they guide me to populate the database with the following data: import { collection, doc, setDoc } from "firebase/firestore"; const citiesRef = collection(db, " ...

Executing a particular end-to-end test case using Angular 2, Karma, and Protractor

Is there a specific command I can use to run an individual e2e test case from my test suite? If that's not possible, is there some workaround for running a specific test suite? I'm currently using Jasmine, Karma, and Protractor. To start my tes ...

Testing Angular components that have protected @Input properties

Typically, we designate variables as protected when they are only used within a component and its subclasses, but not in the template itself. This approach becomes particularly advantageous when a class contains multiple variables, as it makes it easy to ...

Utilizing Typescript to retrieve a specific object property using square brackets and a variable

How can we correctly access a JavaScript object in TypeScript using variable evaluation with bracket notation, such as myObject[myVariable], when the value of the variable is unknown initially? In the code below, an error occurs due to the uncertainty of ...

What is the way to create a `Partial<T>` specifically for nullable fields?

I have a requirement for a custom Partial<T> type that can transform nullable fields into optional ones. Currently, I am focusing on typing our ORM, which converts undefined values to null for nullable fields. In particular, I want to modify a type ...

Explore Angular 4 - Retrieve the guidelines based on their titles within the scss document

I am in search of a reliable method to extract a rule by class selector from a .scss file in order to display it on the Angular app ui. So far, I have not been able to find a suitable parser for .scss that can be used specifically for retrieving a class ru ...

Unexpected runtime error when using Prisma with NodeJS and Express

While starting the server, I encounter an error message saying [ERROR] 14:48:46 Error: Cannot find module './runtime/library'. The stack trace points to the directory named prisma. Even after executing npx prisma generate, the directory called p ...

How should one go about properly implementing the ng2 sequence to refresh a component display based on a dropdown selection?

How can I properly refresh a component's display in ng2 based on dropdown selection? Within my application, there is a users.component and a users.service responsible for searching for users based on a provided request object. Within the users compon ...

What is preventing the route with parameters from functioning properly in Angular2?

I'm currently working on implementing a basic route with a parameter in Angular2. My setup involves Angular 2.0.0-rc.2 and angular router 3.0.0-alpha.7. I've mostly relied on the updated routing documentation available at https://angular.io/docs/ ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...

Screen a roster for shared elements with another roster

Within my dataset, I am working with a List of Objects that adhere to the following Model structure: export class Animal{ public aniId: number; public aniName: string; } export Class Zoo{ public id: number; public name:string; public aniId: number ...

Tailored production method based on specific criteria

One of my challenges is to create a versatile factory method using typescript. The main objective is to initialize a class based on its name using generics, instead of employing if/else or switch statements. I am aiming for similar functionality as this ...

What could be causing the inability to update a newly logged-in user without refreshing the page?

Hello, I have encountered an issue with my application that involves registration and login functionality. The problem arises when a new user logs in, as I must refresh the page to get the current user information. I am currently using interpolation on the ...

Is it possible to set specific points within a Points object in THREE.js to be transparent or invisible?

I am working with a Three.js Points object that holds information for displaying multiple points in 3D space. I am looking for a way to dynamically hide certain points, but I am uncertain of the process. The PointsMaterial used has xyz data stored in poin ...