0

I have 2 different component, which is of different modules too. now i am saving data in one component, that saved data must be fetched to the other component. How can i fetch data from component to component, Please help.

First component:

saveSidebar() {
    let params = { userGuID: this.uID, MenuIds: this.selectedMenuIds.toString() }
    console.log(params);
    this._Service.addUserMenu(params).subscribe((res) => {
      if (res.Header.Success) {

      }
    })
  }

Here the saved data must go to menu component which is in different component

Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88
  • 1
    simply define a shared service, send data to it and get from it. see https://stackblitz.com/edit/angular-shared-service?file=app%2Fapp.component.ts – Fateme Fazli Dec 11 '18 at 11:58
  • You can use `share service` , or you can implement the `redux` for sharing data or called state management. this will make you application more scalable – Sunny Goel Dec 11 '18 at 12:03
  • Possible duplicate of [How do I share data between components in Angular 2?](https://stackoverflow.com/questions/31026886/how-do-i-share-data-between-components-in-angular-2) – Zze Dec 11 '18 at 12:04

4 Answers4

2

You can use a service which is imported in both components and its data shared. So then you can update the service from the first component, then create an event listener on the other component which listens to the changes of the service and updates the ui/data accordingly.

andrea-f
  • 1,045
  • 9
  • 23
0

For parent-child communication you can use @input() @output(); For others, you can use services, register the service in parent module or root module, to learn more please visit below link. https://blog.nrwl.io/essential-angular-dependency-injection-a6b9dcca1761

Akshay Rajput
  • 1,978
  • 1
  • 12
  • 22
0

If multiple modules are using the same variable data, then it is better create a service in the app-root level, modify and access its variables wherever required in your project, a sample code of service

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

      @Injectable({
      providedIn: 'root'
      })
      export class UserinfoService {
        public userName : string = 'username'
      }

making the service injectable in the root level is necessary in order to access it all over the project.

this is yash
  • 533
  • 1
  • 3
  • 15
0

You can use subjects or behavioral subjects. As change in one component will automatically get reflected in other component using subjects.

Abhishek
  • 61
  • 2
  • 8