2016-08-22 6 views
0

Я использую 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», все будет работать как исключено, а мой список с элементами данных отображает все элементы.

Кто-нибудь знает, почему я не могу обновить строку?

Заранее благодарен!

ответ

1

Если вы копируете объект или массив, вы копируете ссылку. Оба (источник и пункт назначения) указывают на один и тот же объект. Если одна сторона изменяет объект, другая сторона видит модификацию.

Если вы копируете примитивное значение (string, number, boolean), получатель получает копию значения, а источник и пункт назначения никак не связаны.

// copies a reference 
    this.data = this._sharedService.dataArray; 
    // copies the value 
    this.title = this._sharedService.testTitle; 

Возможно, что вы, возможно, захотите, это событие, которое испускает события, когда свойства в общей службе изменены.

Для получения дополнительной информации см. https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Смежные вопросы