如何在面對多個組件之間的交互時決定選擇哪種方式?如何確定在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()?爲什麼?
那是因爲你有'SharedService'在'提供商:[...]'ChildCMP'的'。 Angular DI爲每個提供者維護一個實例。在你的情況下'ParentCMP'和'ChildCMP'有'SharedService'兩個不同的實例。將它從子組件中移除,DI向上查找提供程序的根組件,並在「ParentCMP」中找到將導致使用同一實例的那個組件。 –