简体   繁体   English

如何在angular2中将一个组件连接到另一个组件

[英]How to connect from one component to other in angular2

I have 2 different component, which is of different modules too. 我有2个不同的组件,也有不同的模块。 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 这里保存的数据必须转到menu component中的其他组件

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. 因此,您可以从第一个组件更新服务,然后在另一个组件上创建一个事件侦听器,以侦听服务的更改并相应地更新ui / data。

For parent-child communication you can use @input() @output(); 对于亲子沟通,您可以使用@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 https://blog.nrwl.io/essential-angular-dependency-injection-a6b9dcca1761

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. 为了在整个项目中都可以访问该服务,有必要在根级别上注入该服务。

You can use subjects or behavioral subjects. 您可以使用主题或行为主题。 As change in one component will automatically get reflected in other component using subjects. 一个组件的更改会自动使用主题反映到另一组件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM