'Angular13: Share functions between components

I have two functions in two differents components, I'd like to share functions between them but I don't understand how to do and applicate it in my project. In a component, I have a getDatasFromMainTable(). And on the other one, I have a getDatasFromArchiveTable(). I tried :

@Input() myFirstComponent!: MyfirstComponent;

and in a function:

this.myFirstComponent.getDatasFromArchiveTable();

But I have a message

Cannot read properties of undefined (reading 'getDatasFromArchiveTable')

I read a lot of things about behaviorSubject, or @Input(), @ViewChild() or onChanges... But I don't know how to applicate it to my project if I need it for this.



Solution 1:[1]

That's the purpose of a service.

Components should be "dumb" in the sense that they don't anything business-wise : they give responsibility to the services. That's what dependency injection is about.

So to share those methods, create a service that contains them, and let your components call those methods on your service.

Solution 2:[2]

You have a lot of way to share data betwen component.

  1. Sharing Data via Input
  2. Sharing Data via ViewChild
  3. Sharing Data via Output() and EventEmitter
  4. Sharing Data with a Service
  5. Share same logic (method) betwen component

In your case the solution would be number 5. If you want to have sharable method (some logic and use it aproach the whole app)

Example of simple service:

import { Injectable } from '@angular/core';

@Injectable()
export class ExampleOfService{


  constructor() { }

  exampleOfFunction() {
   doSomething();
  }

}

And after that you can call your method in every component. You can add pameters etc...

  import { Component, OnInit  } from '@angular/core';
    
  @Component({
   selector: 'app-example-component',
   template:  ['./app-example-component.html'],
   styleUrls: ['./example.component.scss']
    })

export class ExampleComponent implements OnInit{
   constructor(private exampleOfService: ExampleOfService) { }

ngOnInit(){
     //you can subscribe or whatever you need.
     this.exampleOfService.exampleOfFucntion();
     }

  }

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 temp_user
Solution 2 Daniel Vágner