2017-10-14 107 views
0

現在我可以訪問狀態數據,但我只能通過異步提取狀態中的特定數據成員。我是一名Angular和Ngrx初學者(儘管我已經使用了React/Redux),並且希望有人能指出可能是一個明顯的解決方案。我研究了這個問題,並且看到人們將狀態中的某些數據元素用選擇器作爲可能的解決方案。但是,由於我已經有組件類中的狀態,所以我覺得可能有一個簡單的單線程來訪問數據,而且我的ES6 /前端天真不會妨礙使用。在'/ **'前面的組件類中有兩個註釋,我一直試圖訪問這些數據。Angular - 在Ngrx商店中訪問數據元素

TL; DR:我可以使用異步訪問組件HTML中我想要從我的Ngrx存儲中獲取的數據元素,但我不知道如何訪問組件類中的相同數據元素。

組件類:

interface AppState{ 
    view: Object 
} 

@Component({ 
    selector: 'app-content', 
    templateUrl: './content.component.html', 
    styleUrls: ['./content.component.css'] 
}) 
export class ContentComponent implements OnInit { 
    view: Observable<Object> 
    //**I want to be able to have a reference to the viewId and viewData in this class 
    //**so I can dispatch an action using those data fields 

    constructor(private store: Store<AppState>){ 
    this.view = store.select('view'); 
    } 

    ngOnInit() { 
    } 
} 

組件的HTML

<div *ngIf="view | async as v" style="color:black">{{v.viewId}}</div> 

減速機:

import { ActionReducer, Action } from '@ngrx/store'; 
import * as viewIds from './view.ids'; 
import * as actionTypes from './view.actions'; 

const defaultState = { 
    viewId: viewIds.DEFAULT, 
    viewData: {} 
} 

const newState = (state, newData) => { 
    return Object.assign({}, state, newData) 
} 

export function viewReducer(state: Object = defaultState, action: Action) { 
    const data = action.payload; 
    switch (action.type) { 
     case actionTypes.UPDATE_VIEW: 
      return newState(state, { viewId: data.viewId, viewData: data.viewData }) 

     case actionTypes.DO_NOTHING: 
      console.log("Do nothing!") 
      return state; 

     default: 
      return state; 
    } 
} 

回答

0

您可以訂閱您的商店並從中獲取數據,但不要忘記在組件銷燬時取消訂閱。異步在後臺執行此操作,這裏有兩種方法可以從商店中檢索數據。您可以在github's ngrx example app

this.store.select(fromCore.getView).take(1) 
    .subscribe(view=> { 
    this.viewData= view; 
    }); 

///////meth two /////////// 
this.view$ = store.store.select(fromCore.getView); 
this.view$.map(view=> { 
    this.viewData= view; 
}).take(1); 
+0

獲得從NGRX平臺主機一個更好的例子調用取(1)將取消,但你也可以通過調用this.view $ .unsubscribe()當你需要它(在組件通常退訂你在onDestroy上做)。 –