-1

I abstracted some functionality from a component into a separate service, and injected the service into my component in order to use it. The problem I am facing now is that within my service, I need access to an object in my component.

How do I pass this object into my service. Is there a way to inject this object with a custom InjectionToken?

Thanks for any help!

stackblitz example - commented out inflicting code in service

roonz11
  • 795
  • 1
  • 13
  • 24
  • 2
    Maybe just pass the object as an argument to your service method: `service.doSomethingWithOrder(this.order);` [StackBlitz](https://stackblitz.com/edit/so-68868476?file=src/app/order/order.component.ts&devtoolsheight=60) – BizzyBob Aug 20 '21 at 22:49

1 Answers1

0

You only have to change this in your component:

  doSomething() {
    this.service.doSomethingWithOrder(this.order);
  }

and this in your service:

doSomethingWithOrder(order: {
    id: number;
    name: string;
  }) {
    console.log(order.name);
    alert('need access to order here');
  }

but be careful! As it's an object, you pass it as reference. If you modify it in the service, you are modifying the component object as well (the same instance).

  • Thanks, this simple solution is all I needed. I created a setter method within the service and can now use the object where I need it. Cheers! – roonz11 Aug 21 '21 at 02:16