使用ngrx最新版本的Ngrx App始终是未定义的商店对象

时间:2017-08-05 19:21:36

标签: angular redux ngrx ngrx-store ngrx-effects

我有一个简单的应用程序

没有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

在组件

中创建了一个STATE
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;
  }
}

APP.MODULE

StoreModule.forRoot({MainReducer}),
EffectsModule.forRoot([MainEffects])

它转到服务调用我做了一个日志但是在组件中获取它时我得到以下

enter image description here

很抱歉长篇帖子只是想让你知情。

我关注了这段视频https://www.youtube.com/watch?v=lQi5cDA0Kj8 还有这个https://github.com/ngrx/platform/blob/48a2381c212d5dd3fa2b9435776c1aaa60734235/example-app/app/books/reducers/books.ts

1 个答案:

答案 0 :(得分:0)

根据我的经验,我已经创建了一个伪代码,关于你的代码在下面的样子。

  • GetAction应该没有有效负载。正如您所说的那样,只需触发不接受任何输入的Web服务。
  • 您应在error中添加state以跟踪错误。
  • 您应该使用selectors来获取州的价值
  • 您应订阅store,然后分配值。

<强> STATE

export interface FeatureState {
  comp: any;
  error: any;
}

export interface AppState {
  feature: FeatureState
}

操作

export const GET_COMP = 'GET_COMP';
export const SUCCESS = 'SUCCESS';
export const FAILED = 'FAILED';


export class GetAction implements Action {
  readonly type = GET_COMP;
}

export class SuccessAction implements Action {
  readonly type = SUCCESS;

  constructor(public payload: any) {}
}

export class FailedAction implements Action {
  readonly type = FAILED;

  constructor(public payload: any) {}
}

export type Actions =
  | GetAction
  | SuccessAction
;

<强>减速器

export function MainReducer(state = [],action: GetAction) {
  switch (action.type) {
    case SUCCESS:
            return {
                ...state,
                comp: action.payload
            };
    case FAILED:
            return {
                ...state,
                error: action.payload
            };
        default:
            return state;

}

<强> SELECTORS

import { createSelector } from '@ngrx/store';

export const selectFeature = (state: AppState) => state.feature;
export const selectFeatureCount = createSelector(selectFeature, (state: FeatureState) => state.count);

<强> COMPONENT

@Component({
  selector: 'app-competition',
  templateUrl: './component.html',
  styleUrls: ['./component.css']
})
export class Component implements OnInit {

constructor(private action: OurAction , private store: Store){}

    comp:any[];

    ngOnInit(){
        this.store.dispatch(new OurAction.GetAction());
        this.store.select(selectFeature).subscribe(state => {
          this.comp = state.comp;
        });
    }

<强> App.module.ts

StoreModule.forRoot({ feature : MainReducer }),
EffectsModule.forRoot([MainEffects])