【问题标题】:Passing data between two components在两个组件之间传递数据
【发布时间】:2016-07-20 12:09:55
【问题描述】:

我有两个组件,component1 和 component2

component1 包含以下代码

export class CpOne{
   passedValue:number=null;

   setValue(x){
     this.passedValue = x;
   }
}

组件二包含以下代码

import { CpOne }   from './component1'

export class CpTwo{
     constructor(private cp : CpOne){}
}

我想要实现的,是以某种方式在 component2 中调用 component1 的 setValue 方法,或者基本上将数据从 component2 发送到 component1 并将它们存储在 passValue 变量中。

在不使用模板和传递值的情况下,在 angular2 中这样的事情是否可行?

【问题讨论】:

标签: angular


【解决方案1】:

数据共享不能以这种方式工作。要在组件之间共享数据,您可以使用:

- @ViewChild/@ViewChildren
- Services
- @Input
- Observables

【讨论】:

    【解决方案2】:

    如果您想在不使用@intput/@output 的情况下这样做,我看到两个选项:

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      全球答案是利用共享服务并使用它在组件之间进行通信。

      大多数时候,您需要在引导应用程序时定义共享服务:

      bootstrap(AppComponent, [ SharedService ]);
      

      不要在组件的providers 属性中再次定义它。这样,您将拥有整个应用程序的单个服务实例。

      你可以这样实现共享服务:

      export class SharedService {
        valueUpdated:Subject<any> = new Subject();
      
        updateData(data:any) {
          this.valueUpdated.next(data);
        }
      }
      

      要收到通知,只需订阅主题

      constructor(private service:SharedService) {
        this.service.valueUpdated.subscribe(data => {
          // do something
        });
      }
      

      一个组件是AppComponent 的一个子组件,只需像这样删除providers 属性:

      @Component({
        selector : "other",
        // providers : [SharedService], <----
        template : `
          I'm the other component. The shared data is: {{data}}
        `,
      })
      export class OtherComponent implements OnInit{
        (...)
      }
      

      这样,它们将为两个组件共享相同的服务实例。 OtherComponent 将使用父组件中的那个 (AppComponent)。

      这是因为 Angular2 的“分层注入器”特性。有关更多详细信息,请参阅此问题:


      通过将父级注入子级,您需要注意循环依赖(使用forwardRef - 请参阅https://angular.io/docs/ts/latest/api/core/index/forwardRef-function.html)。但也有可能是这样的:

      @Component({
        template: `
          <div (click)="onClick()">Click</div>
        `,
        (...)
      })
      export class CpTwo{
        constructor(private cp : CpOne){}
      
        onClick() {
          this.cp.setValue({ value: 'some value' });
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 2019-02-21
        • 2020-02-12
        • 1970-01-01
        相关资源
        最近更新 更多