2

我正在使用 Angular + Redux 构建一个购物应用程序。我想要的是通过调度程序功能在点击时触发“ADD_PRODUCT”操作,但点击产品时我只会收到以下错误:

错误类型错误:无法读取未定义的属性“调度”

我在网上搜索并通过在组件中添加选择装饰器解决了类似的问题。我也是,但仍然得到这个错误。

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>

我做错了什么?如何让调度员正常工作?

4

1 回答 1

3

您忘记将修饰符添加privatengRedux组件构造函数中的参数。

constructor(private _http: Http, private ngRedux: NgRedux<IAppState>) { }
                                 ^^^^^^^
于 2017-11-27T20:38:13.893 回答