-1

I have a service where I set the ID, I get this ID from another component on a click event.

export class MyService {

   id: number;
   constructor() {}

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

The value gets set on this click event I have inside my menu component:

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

which triggers this method inside the menu component:

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

How could I send that same value to another component so I can use it for display in HTML?

class MyComponent implements OnInit
{
   id: number;

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

I've tried it like in the example above but I'm getting "undefined" in the console log.

bobdolan
  • 563
  • 3
  • 9
  • 21

1 Answers1

-1

Edit: Don't use an EventEmitter in a Service, this is just a quick Workaround! This post covers all your needs: Delegation: EventEmitter or Observable in Angular

You could use an EventEmitter in your 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;
  }

And then subscribe to the changes of the property in your detail component:

id: number;
ngOnInit()
   {
    this.ms.idUpdated.subscribe(
        (id) => {
          this.id = this.ms.getId();
          console.log(this.id);
        }
      );
   }
Jeremy
  • 270
  • 5
  • 19
  • Per [the docs](https://angular.io/api/core/EventEmitter) EventEmitter is for use *"by directives and components"*. When writing services you should use regular Subjects and Observables. Also it's unwise to expose the emitter/subject as public; that allows values to be pushed into the stream from outside the service. I wrote a bit about this pattern: https://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html – jonrsharpe Mar 15 '18 at 08:28
  • @jonrsharpe I stand corrected. Edited my answer and will update the code as soon as possible. – Jeremy Mar 15 '18 at 14:13