2016-10-11 18 views
3

如何在面對多個組件之間的交互時決定選擇哪種方式?如何確定在Angular 2中組件之間進行通信的最佳方式?

我讀https://angular.io/docs/ts/latest/cookbook/component-communication.html所有這些我們目前有方法,但根據我們應該決定使用他們的特定一個什麼樣的情況呢?

有人可以舉一些例子?

編輯: 我發現,如果我有一個服務

import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { Subject } from 'rxjs/Subject'; 
import { mA, mB } from '../Model/app.Model'; 

@Injectable() 
export class SharedService { 

    private source = new Subject<mA>(); //copied from the tutorial in Angluar 2 website 
    sourceStream$ = this.source.asObservable(); //make it ovbservable for other components to subscrib to it 

    public serviceFunc(ma: mA) { 
     this.source.next(ma); 
    } 
} 

而一個ParentCMP

import { Component } from '@angular/core'; 
import { mA , mB} from './Model/app.Model'; 
import { SharedService } from './Service/app.SharedService'; 
import { Subscription } from 'rxjs/Subscription'; 
@Component({ 
    selector: 'my-app', 
    templateUrl: '/some/url' 
    , providers: [SharedService] 
}) 

export class ParentCMP { 
    someVarIWantToChange: mA; 

    constructor(private sharedService: SharedService) { 
     sharedService.sourceStream$.subscribe(ma => { this.someVarIWantToChange = ma; 
    }); 
    } 
} 

而一個ChildCMP_Speaker

import { Component, Input, Output, EventEmitter } from '@angular/core'; 
import { mA, mB } from './Model/app.Model'; 
import { SharedService } from './Service/app.SharedService'; //reference the service 

@Component({ 
    selector: 'child-app' 
    , templateUrl: '/some/url' 
    , providers: [SharedService] 
}) 


export class ChildCMP { 
    someValue: mA; //local copy of the mA value 

    constructor(private sharedService: SharedService) { 

    } 

    onClick(value: mA) { 
     this.someValue = value; 
     this.sharedService.serviceFunc(this.someValue); 
    } 
} 

我呼籲的的onClick功能ChildCMP模板頁面,成功完全獲得值mA,以及調用該服務的行被執行。但是,someVarIwantToChange根本不會改變。我做錯什麼了嗎?

,並通過這樣做,就是與使用EMIT,並訂閱發出區別?我應該使用.next()還是.emit()?爲什麼?

+0

那是因爲你有'SharedService'在'提供商:[...]'ChildCMP'的'。 Angular DI爲每個提供者維護一個實例。在你的情況下'ParentCMP'和'ChildCMP'有'SharedService'兩個不同的實例。將它從子組件中移除,DI向上查找提供程序的根組件,並在「ParentCMP」中找到將導致使用同一實例的那個組件。 –

回答

3

如果有一個直接的父子關係(孩子是在父母的模板)使用結合

否則使用共享服務。

如果共享服務的值可以更改,使用可觀察到這樣的組件和興趣在此狀態下服務沒有輪詢,而是可以訂閱的變化得到通知。

更新

那是因爲你在提供商SharedService:[...] ChildCMP的。 Angular DI爲每個提供者維護一個實例。在你的情況下,ParentCMP和ChildCMP有2個不同的SharedService實例。將它從子組件中移除,DI向上查找提供程序的根組件,並在ParentCMP中找到一個將導致使用同一實例的組件。

+0

你是上帝的人。謝謝! –

+0

甚至不敢靠近,只是很多的經驗察覺問題Angular2代碼;-) –

+0

是你點上,使用的輸入/與沒有relatiion組件輸出可以得到真正的混亂和亂! – vicgoyso

相關問題