Search code examples
angulartypescriptfunctionservicereturn-value

Angular - Communication between unrelated components with return value


I´m trying to restructure my project and for that I´m working on how to communicate between components that are not-related and also wait for a return value from the called function.

So let´s say I have a component1 and a function1() and also a component2 and a function2(). In between stands the component.service.

component1:

import { Component, OnInit } from '@angular/core';
import { ComponentService } from '../component.service';

@Component({
  selector: 'component1',
  template: ''
})
export class Component1 implements OnInit {
    
  constructor() {}

  ngOnInit() {
    
  }

  function1() {
    //do something
    
    let parameter: any = "some Parameter";
    let returnValue = function2(parameter);

    //do something else
  }

}

component2:

import { Component, OnInit } from '@angular/core';
import { ComponentService } from '../component.service';

@Component({
  selector: 'component2',
  template: ''
})
export class Component2 implements OnInit {
    
  constructor() {}

  ngOnInit() {
    
  }

  function2(parameter: string) {
    //do something
    
    return parameter + "did something with it";
  }

}

componentService:

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

@Injectable({
  providedIn: 'root'
})
export class ComponentService{

  constructor() { }

  //???
}

How can I achieve this structure so function1() can work with the returned Value from function2(). How do I have to build the service?

Thanks in advance.


Solution

  • you'll never call a function that is inside component2 from component1. this is what the service was created for. every data/logic you need for both components you store it in a service and inject the service to both components.

        @Injectable({
          providedIn: 'root'
        })
        export class ComponentService{
        
          constructor() { }
        
          getSomeData() {
            return '' // return what do you need
     }
        }
    

    and every component:

      @Component({
          selector: 'component2',
          template: ''
        })
        export class Component2 implements OnInit {
        
      constructor(private componentService: ComponentService) {}
    
      ngOnInit() {
        
      }
    
      function2(parameter: string) {
        //do something
        
        return this.componentService.getSomeData()
      }
    
    }