1
I’d like to pass a service as a parameter between two components, from father to son. The communication between the components is okay, I am receiving the service, but when I try to use the functions within the service it is as if they do not exist. Remembering that I want to spend the entire service (so it doesn’t have to matter) and not just its name.
Example
Parent.component.ts
Import { Service} from '../_service/service.service';
...
@ViewChild('child') child:ChildComponent;
constructor(private service:Service) {
}
ngOnInit() {
//pelo componente pai estou enviando o service como parâmetro ao filho, tudo okay ele recebe l
this.child.setService(Service);
}
Child.component.ts
...
private serviceElement;
ngOnInit() {
useService();
}
setService(service:any) {
console.log(service);
//o retorno do console.log é: Service(http) { this.http = http ....
//ou seja, o service chegou até aqui
return this.serviceElement = service;
}
useService() {
this.serviceElement.list();
//retorna o erro abaixo
}
The error returned when trying to use the service is:
ERROR Error: Uncaught (in Promise): Typeerror: this.serviceElement.list is not a Function
What would be the correct way to pass a service from a parent component to the child as a parameter?
You don’t have to do this, just inject the same service into the other component and ready, they will already share the same instance
– Sérgio S. Filho