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

3
  • 1
    simply define a shared service, send data to it and get from it. see stackblitz.com/edit/… Commented Dec 11, 2018 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 Commented Dec 11, 2018 at 12:03
  • Possible duplicate of How do I share data between components in Angular 2? Commented Dec 11, 2018 at 12:04

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i have tried in this way only, but i am not able to get data as i need
@Bhrungarajni can you share the code you are trying?
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

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.