现在,我可以访问状态数据,但我只能通过异步提取状态内的特定数据成员。我是一个角度和Ngrx初学者(虽然我已经使用了React/Redux一点),并希望有人能指出什么可能是一个明显的解决方案。我已经研究过这个问题,并且看到人们在状态中为某些数据元素使用选择器作为可能的解决方案。但是,由于组件类中已经有了状态,所以我觉得可能有一个简单的一行程序来访问数据,而我的es6/前端天真则排除了使用。组件类中有两个注释与'//**‘放在前面,我一直试图访问这些数据。
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() {
}
}组件
<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;
}
}发布于 2017-10-16 20:26:05
您可以订阅您的存储并从中获取数据,但是当组件被破坏时不要忘记取消订阅。异步在后台这样做,以下是从存储中检索数据的两种方法。您可以从github的ngrx示例应用程序的ngrx平台上获得一个更好的示例。
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);https://stackoverflow.com/questions/46750091
复制相似问题