Home > database >  Angular13: Share functions between components
Angular13: Share functions between components

Time:04-28

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.

CodePudding user response:

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.

CodePudding user response:

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

  }
  • Related