2个组件之间的Angular2通信
问题描述:
我正在使用Angular2 rc5,并尝试通过服务构建组件通信。 对于数组,它像预期的那样工作,但如果我更改一个字符串,它不会更新。2个组件之间的Angular2通信
我的主要成分是这样的:
import {Component} from '@angular/core';
import {ShareServiceService} from "../share-service.service";
import {ChildTwoComponent} from "../child-two/child-two.component";
import {ChildOneComponent} from "../child-one/child-one.component";
@Component({
selector: 'parent',
template: `
<h1>Parent</h1>
<div>
<child-one></child-one>
<child-two></child-two>
</div>
`,
providers: [ShareServiceService],
directives: [ChildOneComponent, ChildTwoComponent]
})
export class ParentComponent {
constructor() {}
}
我的第一个孩子组件:
import {Component} from '@angular/core';
import {ShareServiceService} from "../share-service.service";
@Component({
selector: 'child-one',
template: `
<div style="float:right; width: 45%">
<pre>title: {{title}}</pre>
<pre>title: {{_sharedService.testTitle}}</pre>
<div>
<ul *ngFor="let dataElement of data">
<li>{{dataElement}}</li>
</ul>
</div>
</div>
`
})
export class ChildOneComponent{
data:string[] = [];
title:string;
constructor(public _sharedService:ShareServiceService) {
this.data = this._sharedService.dataArray;
this.title = this._sharedService.testTitle;
}
}
第二个孩子组成:
import {Component} from '@angular/core';
import {ShareServiceService} from "../share-service.service";
@Component({
selector: 'child-two',
template: `
<div style="float:left; width: 45%">
<pre>title: {{title}}</pre>
<pre>titleObj: {{titleObj.title}}</pre>
<div>
<ul *ngFor="let dataElement of data">
<li>{{dataElement}}</li>
</ul>
</div>
<input type="text" [(ngModel)]="dataInput"/>
<button (click)="addData()">addData</button>
<button (click)="updateTitle()">updateTitle</button>
</div>
`
})
export class ChildTwoComponent {
dataInput:string = 'Testing data';
data:string[] = [];
title:string;
constructor(public _sharedService:ShareServiceService) {
this.data = this._sharedService.dataArray;
this.title = this._sharedService.testTitle;
}
addData() {
this._sharedService.insertData(this.dataInput);
this.dataInput = '';
}
updateTitle() {
this._sharedService.updateTestTitle(this.dataInput);
this.dataInput = '';
}
}
我的服务:
import {Injectable} from '@angular/core';
@Injectable()
export class ShareServiceService {
dataArray:string[] = [];
testTitle:string = "should be updated";
insertData(data:string) {
this.dataArray.push(data);
}
updateTestTitle(newTitle:string) {
this.testTitle = {title: newTitle};
}
}
我试图实现的是,如果我在输入字段中输入绑定“”的内容并按下两个组件中的标题更新的“updateTitle”。 但目前不工作。
如果我通过点击“adddata”按钮将我的输入值添加到一个数组,所有作品像例外和我的数据元素列表显示所有元素。
有人知道我为什么不能更新字符串吗?
在此先感谢!
答
如果复制对象或数组,则复制引用。 (源和目的地)都指向同一个对象。如果一方修改对象,则另一方会看到修改。
如果复制原始值(字符串,数字,布尔值),则目标将获取该值的副本,并且源和目标之间没有任何关联。
// copies a reference
this.data = this._sharedService.dataArray;
// copies the value
this.title = this._sharedService.testTitle;
你可能想要的是一个observable,它在共享服务中的属性被修改时发出事件。
详情请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service