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」ボタンをクリックすると、配列に入力値を追加すると、すべてがexceptedのように動作し、データ要素のリストにすべての要素が表示されます。
誰かが文字列を更新できない理由を知っていますか?
ありがとうございます!