2017-05-07 17 views
0

我想將存儲在Redux中的對象數組下載到Angular 2組件中,然後遍歷每個數組的對象並在其上執行一些操作它將結果存儲在組件中。一個例子:將Redux狀態下載到Angular 2組件中,然後迭代其結果

import { Component } from '@angular/core'; 
 
import { Store } from '@ngrx/store'; 
 
import { AppStore } from './app-store'; 
 

 
@Component({ 
 
    selector: 'selector', 
 
    templateUrl: './templateUrl.html' 
 
}) 
 
export class Component { 
 

 
    sum : number = 0; 
 
    arrayFromRedux$; 
 
    
 
    constructor(
 
    private store: Store<AppStore> 
 
) { 
 
    this.arrayFromRedux$ = this.store.select('dataFromReduxStore') 
 
    .subscribe(data => this.sum = data.reduce((a,b) => a.number+ b.number)); 
 
    } 
 

 
}

從存儲數據:

[ 
 
    { 
 
    "name": item1, 
 
    "number": 3 
 
    }, 
 
    { 
 
    "name": item2, 
 
    "number": 5 
 
    }, 
 
    { 
 
    "name": item3, 
 
    "number": 1 
 
    }, 
 
]

我想總和爲等於9.

部分問題的我認爲組件將數據作爲可觀察的流接收,並且在迭代中存在一個複雜的問題。

即時錯誤我得到的是TS錯誤:「[ts]屬性'reduce'在類型'{}'上不存在」。這出現在試圖對數據執行減少操作。嘗試過這種變化,並沒有遇到任何似乎工作的東西。

謝謝!

回答

0

我相信你應該在ngOnInit期間訂閱你的observable。另外,以$結尾的變量通常是可觀察的流,而不是訂閱。

我對你的data.reduce函數有問題,所以我修改了它。

import { Component } from '@angular/core'; 
 
import { Store } from '@ngrx/store'; 
 
import { AppStore } from './app-store'; 
 

 
@Component({ 
 
    selector: 'selector', 
 
    templateUrl: './templateUrl.html' 
 
}) 
 
export class Component { 
 

 
    sum : number = 0; 
 
    arrayFromRedux$; 
 
    mySubsription; 
 
    
 
    constructor(
 
    private store: Store<AppStore> 
 
) { } 
 

 
    ngOnInit() { 
 
    this.arrayFromRedux$ = this.store.select('dataFromReduxStore'); 
 
    this.mySubscription = this.arrayFromRedux$ 
 
     .subscribe((data: Array<Object>) => this.sum = data.reduce((acc, item) => acc + item.number, 0); 
 
    } 
 
    ngOnDestroy() { 
 
    this.mySubsription.unsubscribe(); 
 
    } 
 

 
}

+0

感謝這個! –