1
votes

I have a Simple App

Without NGRX

Component

@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)}

Service

@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())
  }

All these works Fine when i try to convert it to ngrx it dosent work using store and effects.

USING NGRX

Created a STATE in component

export interface AppState{
    comp:any;
}

ngOnInit(){
        this.store.dispatch({type:GET_COMP,payload: {}});
}

ACTIONS

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
;

EFFECTS

@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}))  
      );
}

REDUCER

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])

It goes to the Service call i did a log but while getting it in component i get the following

enter image description here

Sorry for the long post just wanted to keep you informed.

I Followed this video https://www.youtube.com/watch?v=lQi5cDA0Kj8 and also this https://github.com/ngrx/platform/blob/48a2381c212d5dd3fa2b9435776c1aaa60734235/example-app/app/books/reducers/books.ts

1
Read this medium postAravind
@Aravind Same thing aravind i registered the reducer that was missing in Action Reducer Map but no effect . I get the same Store scalr properties in console where is the object . that i get from database ? that causes my ngfor to throw error saying its only for array not for object objectINFOSYS
The only thing different in my case is i dont have a model i use any in comp , how to use this with any type ? please helpINFOSYS
where are you using any type?Aravind
If you see the appstate it has a property of comp:anyINFOSYS

1 Answers

1
votes

I as per my experience have created a pseudo code, as to how your code should look like below.

  • GetAction should have no payload. As you are calling it to just fire the web service which does not takes any input.
  • You should add error in your state to keep tracks of errors.
  • You should use selectors to get the value of the state
  • You should subscribe to the store and then assign the values.

STATE

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

export interface AppState {
  feature: FeatureState
}

ACTIONS

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
;

REDUCER

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])