Angular 12 - how do you pass an object into your service

694 Views Asked by At

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

1

There are 1 best solutions below

1
On BEST ANSWER

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).