我有一个简单的应用程序
没有 NGRX
零件
@Component({
selector: 'app-competition',
templateUrl: './component.html',
styleUrls: ['./component.css']
})
export class Component implements OnInit {
constructor(private Service:Service){}
comp:any[];
ngOnInit(){this.Service.get().subscribe(comp => this.comp)}
服务
@Injectable()
export class CompetitionService{
constructor(private http:Http, private af: AngularFireDatabase){
}
getComp(){
let headers = new Headers();
headers.append('X-Auth-Token', 'XXXXX');
return this.http.get('URL',{headers:headers}).map(response => response.json())
}
当我尝试将其转换为 ngrx 时,所有这些工作都很好,它使用存储和效果来工作。
使用 NGRX
在组件中创建了一个状态
export interface AppState{
comp:any;
}
ngOnInit(){
this.store.dispatch({type:GET_COMP,payload: {}});
}
行动
export const GET_COMP = 'GET_COMP';
export const SUCCESS = 'SUCCESS';
export class GetAction implements Action {
readonly type = GET_COMP;
constructor(public payload: any) {}
}
export class SuccessAction implements Action {
readonly type = SUCCESS;
constructor(public payload: any) {}
}
export type Actions =
| GetAction
| SuccessAction
;
效果
@Injectable()
export class MainEffects {
constructor(private action$: Actions, private service$ :CompetitionService ) { }
@Effect() load$:Observable<Action> = this.action$
// Listen for the 'LOGIN' action
.ofType(GET_COMP)
.switchMap(action => this.service$.getComp()
// If successful, dispatch success action with result
.map(res => ({ type: SUCCESS, payload: res}))
// If request fails, dispatch failed action
.catch((err) => Observable.of({ type: 'FAILED' ,payload :err}))
);
}
减速器
export function MainReducer(state = [],action: GetAction) {
switch (action.type) {
case GET_COMP:
return [action.payload];
default:
return state;
}
}
应用程序模块
StoreModule.forRoot({MainReducer}),
EffectsModule.forRoot([MainEffects])
它转到服务调用,我做了一个日志,但是在组件中获取它时,我得到以下信息
很抱歉,这篇长文只是想让您了解情况。
我关注了这个视频https://www.youtube.com/watch?v=lQi5cDA0Kj8 和这个https://github.com/ngrx/platform/blob/48a2381c212d5dd3fa2b9435776c1aaa60734235/example-app/app/books/reducers/books。 ts