0

I want to manipulate the value of some local variables from the service which a component calls .

Yes , it can be done by subscribing(in component) to an Observable (in service) but i don't want to add anything in the component .

updating variable changes in components from a service with angular2

which proposes this :

component {
     service.subject.subscribe (_=>{--do stuff here --})
} 
Service {
     subject() -- An observable --
}

I want the service to be responsible for setting some of my local variables (in component) .

Something like this :

Service -- > Call some component' variable and set it !

Can this be done ? If yes then how ?

Aakash Uniyal
  • 1,519
  • 4
  • 17
  • 32

1 Answers1

1

The whole idea of using services is to make them independent and reusable. So your idea of having a service to modify the properties of a component introduces tight coupling between the service and component.

If you still want to do this, then create a setter on this service and invoke it from your component passing the reference to the component instance, e.g.

myService.setComponent(this);

Then you'll be able to modify properties of the component from the service. But again, I wouldn't recommend going this route.

Yakov Fain
  • 11,972
  • 5
  • 33
  • 38
  • Thanks for the swift answer Yakov . Yes true , it will lead to tightly coupled entities . What i actually plan to do with this is to create a Component Manipulator service specifically for this which other services would use . Basically what i am creating is some modules which by default takes care of some redundant stuff like showing 'Http request related Errors' without making the component write for it (Choice). – Aakash Uniyal Jun 22 '17 at 11:30
  • If you're going to proceed this route, create an interface declaring a method setErrors() and have each of your components implement it so your service will invoke the same method on each component. This will somewhat reduce the tight coupling. – Yakov Fain Jun 22 '17 at 13:48