我有一个 Angular 2 的父组件,有两个 sibling 的子组件。 Sibling1 有一个按钮,Sibling2 只有一个 h1 元素,当按下 Sibling1 中的按钮时,该元素应该更改其文本。我听说最好的方法是使用共享服务。但我无法弄清楚。按下按钮后文本不会更改。
父级
导入 SharedService 并将其作为提供者
模板:
<sibling1></sibling1>
<sibling2></sibling2>
共享服务
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
private text = new Subject<string>();
text$ = this.text.asObservable();
publishText(textToPublish: string){
this.text.next(textToPublish);
}
sibling 1
import {SharedService} from './shared.service';
<button (click)="onClick()">press me</button>
export class Sibling1{
constructor(private ss: SharedService){}
onClick(){
this.ss.publishText('sample text');
}
}
sibling 2
import {SharedService} from './shared.service';
<h1>{{text}}</h1>
export class Sibling2{
text: string;
constructor(private ss: SharedService){
ss.text$.subscribe(data => this.text = data);
}
}
模块
导入 ParentComponent、Sibling1、Sibling2 和 SharedService
并且有声明:ParentComponent、Sibling1、Sibling2
和提供者:[SharedService]
我也不确定需要在应用程序模块和父组件中声明哪些导入和提供程序。谢谢。
最佳答案
我创建了一个 plknr 应该可以帮助你。看看http://plnkr.co/edit/60ncOxHwiOy8biiUc9mt?p=info
正如 AJT_82 所说,您可能忘记添加提供者:[SharedService]
更新
我更新了 plunker,以便使用 ngOnInit
获取订阅,并使用 ngOnDestroy
以便在组件被销毁时取消订阅。
关于javascript - 在 Angular 2 中的同级组件之间交换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555259/