在两个组件

时间:2016-07-20 12:09:56

标签: angular

我有两个组件,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并将它们存储在passedValue变量中。

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

由于

3 个答案:

答案 0 :(得分:0)

数据共享不起作用。要在可以使用的组件之间共享数据:

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

答案 1 :(得分:0)

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

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

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)中的那个。

这是因为&#34;分层注射器&#34; 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' });
  }
}

答案 2 :(得分:0)

如果您想在不使用@intput / @output的情况下执行此操作,我会看到两个选项:

希望它有所帮助。