'Angular 6: Passing object from component to service

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.



Solution 1:[1]

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;
}

Solution 2:[2]

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)

Solution 3:[3]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fateme Fazli
Solution 2 Vikas
Solution 3