javascriptangularreduxdispatcherangular-redux

Angular / Redux Cannot read property 'dispatch' of undefined


I am building up a Shopping app with Angular + Redux. What I want is to fire the "ADD_PRODUCT" action on click through a dispatcher function, but I only get the following error when click on a product:

ERROR TypeError: Cannot read property 'dispatch' of undefined

I searched in the net and similar issues were solved by adding select decorator in the component. So did I, but still get this error.

store.ts

import { IProduct } from './product';
import { ADD_PRODUCT, REMOVE_PRODUCT, REMOVE_ALL_PRODUCTS } from './actions';

export interface IAppState {
    products: IProduct[];
}

export const INITIAL_STATE: IAppState = {
    products[]
}

const productsReducer = (state=[], action) => {
    switch(action.type) {
        case "ADD_PRODUCT" : {
            state = {...state, products: action.payload}
            break;
        }
    }
    console.log("Products Reducer!")
    return state;
}

const cartReducer = (state=[], action) => {
    console.log("Cart Reducer!")
    return state;
}

// Reducers
export const rootReducer = () => ({ 
    products: productsReducer,
    cart: cartReducer
})

store.component.ts

import { Component, OnInit } from '@angular/core';
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from '../store';
import { ADD_PRODUCT } from '../actions';
import { IProduct } from '../product';
import { Router } from "@angular/router";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, HttpModule, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';

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

  @select() prod;
  private products = new BehaviorSubject<any>([]);

  product = this.products.asObservable();
  dataUrl = "./assets/products.json";
  prods: any;

  constructor(private _http: Http, ngRedux: NgRedux<IAppState>) { }

  getProducts(): Observable<any>{
      return this._http.get(this.dataUrl)
      .map((res: Response) => res.json());
  }

  ngOnInit() {
    this.getProducts().subscribe(prods => this.prods = prods);
  }

  addToCart(prod){
    this.ngRedux.dispatch({type: "ADD_PRODUCT", payload: prod})
    console.log(prod.title + " added!")
  }

}

store.component.html

<div class="container">
    <div class="row">
        <div *ngFor="let prod of prods" class="col-sm-4 col-md-4 col-lg-4">
        <div class="addBtn" (click)="addToCart(prod)">Add product</div>
     </div>
   </div>
</div>

What I am doing wrong? How to make the dispatcher work correctly?


Solution

  • You forgot to add private modificator to ngRedux param in component constructor.

    constructor(private _http: Http, private ngRedux: NgRedux<IAppState>) { }
                                     ^^^^^^^