在Angular2中,使用服務在組件之間共享數組數據?Angular 2,如何在使用服務的組件之間共享數組數據?
object structure
{
data: 'data'
keys: ['key1', 'key2', ... , 'keyN']
}
* Service has a array of total objects.
totalObject = [object1, object2, ... , objectN]
起初我初始化服務selectedObject這樣。
selectedObject = totalObject;
然後,我像這樣在構造函數上初始化了Component的selectedObject。
constructor(private wordService: WordService) {
this.words = wordService.selectedWords;
}
首先,組件B顯示所有對象正確! 但是,當服務將新數組初始化爲selectedObject時,組件B將無法顯示選定的對象。
// It's not working...
// remove
this.selectedWords.splice(0, this.selectedWords.length);
// add
for(let i in WORDS) {
if(WORDS[i].keys.indexOf(key) >= 0) {
this.selectedWords.push(WORDS[i]);
}
}
而不是重新創建陣列,空它,推送新項目或始終引用wordService.selectedWords。我會選擇第二個選項。 –
@KasperZiemianek感謝您的評論!我理解第一個選項,但第二個選項中的「始終參考」是什麼意思? –
@KasperZiemianek我用第一個選項,但它不工作。添加代碼。 –