【问题标题】:How to Share Data between Components in Angular2 [duplicate]如何在Angular2中的组件之间共享数据[重复]
【发布时间】:2018-01-30 21:12:04
【问题描述】:

在这个场景中,我有 3 个组件,即组件 1、组件 2、组件 3。 Component-2 和 Component-3 托管在 Component-1 中 我想在单击组件 2 中的按钮后将数据发送到组件 3。 提前致谢

【问题讨论】:

  • 我已添加图片供参考
  • 您可以在 Angular 2 中使用 @Input@Output 在组件之间进行通信。
  • 使用 Rxjs 主题,行为主题是您场景的最佳解决方案。

标签: javascript angular typescript angular2-services angular2-directives


【解决方案1】:

使用服务在组件之间共享数据。

服务

 export class MyService {
     public someVariable: string = ""
     // .....
 }

组件 1(打字稿)

 import { MyService } from "./myService.service"
 // ......
 constructor(public ms: MyService) {}

 setValue(val){
     this.ms.someVariable = "Hello!" // Alter the variable in the service
 }

组件 2(打字稿)

 import { MyService } from "./myService.service"
 // ......
 constructor(public ms: MyService) {}

组件 2 (HTML)

 <h1>{{ ms.someVariable }}</h1>  <---- Will print Hello! in your HTML markup

【讨论】:

    【解决方案2】:

    您可以使用 Angular 2/4 中可用的 @Input 和 @Output 装饰器方法来实现这一点。

    这些使用起来非常简单。只需将共享数据保留在组件 1 中,然后将该数据与组件 2 和 3 进行双向绑定。确保在组件 2 或 3 中的任何一个数据发生更改时触发更改事件。

    //for example component 1
    @Component({ ... })
    
    export class Component1{
      private data: Data = "some data";
    }
    
    //component 2 and 3
    @Component({ ... })
    
    export class Component2{
    
      @Input() data: Data = "some data";
      @Output() dataChange: EventEmitter ...
      
      ngOnChanges(){
        this.dataChange.emit(this.data);
      }
    }
    <component1>
    <component2 [(data)]="data"></component2>
    <component3 [(data)]="data"></component3>
    </component1>

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 2017-10-25
      • 2017-06-26
      • 2016-05-18
      • 2017-07-22
      • 2017-09-29
      • 2021-11-11
      • 2017-03-06
      相关资源
      最近更新 更多