Angular 7: pass the service from one component to another per parameter

Asked

Viewed 1,339 times

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

3 answers

1

Sharing my solution with you, I implemented the suggestion given above, but the component I was making has a Child with ngIf always came Undefined, and I cannot inject fixed service in them, because I will use customizable data... the Behaviorsubject solution

export class MidiasDistribuicaoComponent implements OnInit {
    contextoConfig: any;
    contextoBehaviorSubject = new BehaviorSubject<any>('contexto');

    constructor(private midiasDistribuicaoService: MidiasDistribuicaoService) {
        this.contextoConfig = {
            values: MidiasDistribuicaoValues,
            service: this.midiasDistribuicaoService
        };
    }

    ngOnInit() {
        this.contextoBehaviorSubject.next(this.contextoConfig);
    }

}

and then input-Property into Child, receive the observable, and click on onInit

<app-manager [contextBehaviorSuject]='contextBehaviorSubject'>

and on Child ts:

ngOnInit(): void {
    this.contextoBehaviorSuject.subscribe(contextoConfig => {
        this.contextoService = contextoConfig.service;
        this.values = contextoConfig.values;
    });

}

ready ... I can share complex data between components with a content generator (Behavior Subject) and the children of the children can also use is only rececer by inputProperty and subscribe to onInit. more information about the observable in

https://dev.to/felipedsc/behaviorsubject-para-comunicacao-entre-componentes-3kpj

1

As you have previously passed the Service as import, you may need to start a variable with a new of that service. In Dad you didn’t need to start as new because it is in the constructor that already solves this action without you having to write it.

1


I found a way to do this, the only modification for in the code above is to instead of passing the Service, have to pass the service, the service call of the parent component.

Before

this.child.setService(Service);

Afterward

this.child.setService(service);

Now I can access the service injected into the parent by the child component.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.