1

I want to pass my object from component to service class. I know there are some possible ways in angular series, but you can suggest me a good method to achieve this goal, big thanks for good suggestions and codes.

1
  • 1
    Can you share the piece of code with us, Enrique? Commented Jun 29, 2018 at 14:21

3 Answers 3

4

you should simply define a setter getter for your service:
component:

constructor(private myService:MyService){}
ngOnInit(){
    this.myService.setData(this.obj);
    this.myServcie.getData();
}

MyService:

setData(obj){
    this.obj = obj
}

getData(){
    return this.obj;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, but i want to pass my object from a function, the function get that data from an emitter, that local data should be passed to the service,possible?
@Enrique_Iglesias yes it's possible you can call the setter getter of service in every function you want.
0

you can use either @Input() and @Output variables. @Input() for passing data from parent to child component, and @Output() to emit an event from child component to parent component. For @Output() you must listen to the emitted event in parent component.

Also, you can use a shared service as mentioned and return observables using subjects.

private subject = new Subject();
public obsForComponent = this.subject.asObservable();

setValue(condition: any){
    this.subject.next(condition) // Sets the new Observable value that can be listened in components 
}

In your component on ngOnit or in the template just reference the service.ObsForComponent.subscribe(value=>...), and if you want to set/emit new obs, service.setValue(something)

Comments

0

Like Fateme said you can use setter and getter but as follows:

Component:

yourHandler() {
  this.service.myfunc = {
    property1: "SomeValue",
    property2: "AnotherValue"
  }
}

Service:

object: {};

set myfunc({...obj}) {
  this.object = {...obj}
}

get myFunc(): {} {
  return this.object
}

And just use myFunc in your other components, without parentheses ()

for example:

From any components:

myObj: {};

constructor(private service: MyService) {
  this.myObj = this.service.myFunc;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.