【发布时间】:2016-12-29 07:04:37
【问题描述】:
我正在使用 Angular2 rc5,我尝试通过服务构建组件通信。 对于数组,它按预期工作,但如果我更改一个字符串,它不会更新。
我的主要组件看起来像:
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”按钮,所有工作都像例外一样,我的数据元素列表显示所有元素。
有人知道我为什么不能更新字符串吗?
提前致谢!
【问题讨论】:
标签: data-binding angular typescript