Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ngrx/存储角度-状态未保留某些数据_Javascript_Angular_Typescript_Ngrx - Fatal编程技术网

Javascript ngrx/存储角度-状态未保留某些数据

Javascript ngrx/存储角度-状态未保留某些数据,javascript,angular,typescript,ngrx,Javascript,Angular,Typescript,Ngrx,我有一个购物商店应用程序,我在其中管理产品状态和购物车状态 在加载产品页面时,我从服务器获取所有产品,并在redux开发工具中查看它们。 一旦我将一个项目添加到购物车中,购物车状态就会更新,但是该状态中的所有产品都丢失了,我在页面上再也看不到它们了 将项目添加到购物车之前: 将项目添加到购物车后: 如何在不删除产品状态的情况下将项目添加到购物车中,使其不会为空 app.state: import { CartState } from './cart/cart.state'; import P

我有一个购物商店应用程序,我在其中管理产品状态和购物车状态

在加载产品页面时,我从服务器获取所有产品,并在redux开发工具中查看它们。 一旦我将一个项目添加到购物车中,购物车状态就会更新,但是该状态中的所有产品都丢失了,我在页面上再也看不到它们了

将项目添加到购物车之前:

将项目添加到购物车后:

如何在不删除产品状态的情况下将项目添加到购物车中,使其不会为空

app.state:

import { CartState } from './cart/cart.state';
import ProductState from './product/product.state';

export interface AppState {
  product: ProductState;
  cart: CartState;
}
应用程序:减速器

import { cartReducer } from './cart/cart.reducers';
import { productReducer } from './product/product.reducers';

export const appReducers = {
  product: productReducer,
  cart: cartReducer
};
行动

import { Action } from '@ngrx/store';
import { CartProductModel } from '../../models/cart/cart.model';

export const ADD_TO_CART = '[CART] ADD';
export const UPDATE_CART = '[CART] UPDATE CART';
export const REMOVE_FROM_CART = '[CART] REMOVE';
export const CLEAR_CART = '[CART] CLEAR';

export class AddToCart implements Action {
  readonly type: string = ADD_TO_CART;

  constructor(public payload: CartProductModel) {}
}

export class UpdateCart implements Action {
  readonly type: string = UPDATE_CART;

  constructor(public id: string, public quantity: number) {}
}

export class RemoveFromCart implements Action {
  readonly type: string = REMOVE_FROM_CART;

  constructor(public id: string) {}
}

export class ClearCart implements Action {
  readonly type: string = CLEAR_CART;
}
大车减速器

import { CartState } from './cart.state';
import { AppState } from '../app.state';
import {
  ADD_TO_CART,
  UPDATE_CART,
  REMOVE_FROM_CART,
  CLEAR_CART
} from './cart.actions';
import { CartProductModel } from '../../models/cart/cart.model';

const initialState: CartState = {
  products: []
};

function addToCart(state: CartState, product: CartProductModel) {
  if (state.products.find(p => p._id === product._id)) {
    const newProducts = state.products.slice();
    const cartProduct = newProducts.find(p => p._id === product._id);
    cartProduct.quantity = +1;
    return {
      ...state,
      products: newProducts
    };
  }


  return {
    ...state,
    products: [...state.products, product]
  };
}

function updateCart(state: CartState, id: string, quantity: number) {
  // debugger
  const newProducts = state.products.slice();
  const cartProduct = newProducts.find(p => p._id === id);
  cartProduct.quantity = quantity;

  return {
    ...state,
    products: newProducts
  };
}

function removeFromCart(state: CartState, id: string) {
  return {
    ...state,
    products: [...state.products.filter(p => p._id !== id)]
  };
}

function clearCart(state) {
  return {
    ...state,
    products: []
  };
}

export function cartReducer(state: CartState = initialState, action) {
  switch (action.type) {
    case ADD_TO_CART:
      return addToCart(state, action.payload);

    case UPDATE_CART:
      return updateCart(state, action.id, action.quantity);

    case REMOVE_FROM_CART:
      return removeFromCart(state, action.id);

    case CLEAR_CART:
      return clearCart(state);
    default:
      return state;
  }
}
import ProductState from './product.state';
import * as ProductActions from './product.actions';

const initialState: ProductState = {
  all: []
};

function getAllProducts(state, action) {
  return {
    ...state,
    all: action
  };
}

function createProduct(state, action) {
  return {
    ...state,
    all: [...state.all, action]
  };
}

function editProduct(state, action) {
  return {
    ...state,
    all: [...state.all.filter(p => p._id !== action._id), action]
  };
}


export function productReducer(
  state: ProductState = initialState,
  action: ProductActions.Types
) {
  switch (action.type) {
    case ProductActions.GET_ALL_PRODUCTS:
      return getAllProducts(state, action.payload);

    case ProductActions.CREATE_PRODUCT:
      return createProduct(state, action.payload);

    case ProductActions.EDIT_PRODUCT:
      return editProduct(state, action.payload);


    default:
      return initialState;
  }
}
购物车状态

import { CartProductModel } from '../../models/cart/cart.model';

export interface CartState {
  readonly products: CartProductModel[];
}
产品行动

 import { Action } from '@ngrx/store';
    import ProductModel from '../../models/product/product.model';

    export const GET_ALL_PRODUCTS = '[PRODUCT] GET ALL';
    export const CREATE_PRODUCT = '[PRODUCT] CREATE';
    export const EDIT_PRODUCT = '[PRODUCT] EDIT';

    export class GetAllProducts implements Action {
      type: string = GET_ALL_PRODUCTS;
      constructor(public payload: ProductModel[]) {}
    }

    export class CreateProduct implements Action {
      type: string = CREATE_PRODUCT;
      constructor(public payload) {}
    }

    export class EditProduct implements Action {
      type: string = EDIT_PRODUCT;
      constructor(public payload) {}
    }



    export type Types = GetAllProducts | CreateProduct | EditProduct;
产品还原剂

import { CartState } from './cart.state';
import { AppState } from '../app.state';
import {
  ADD_TO_CART,
  UPDATE_CART,
  REMOVE_FROM_CART,
  CLEAR_CART
} from './cart.actions';
import { CartProductModel } from '../../models/cart/cart.model';

const initialState: CartState = {
  products: []
};

function addToCart(state: CartState, product: CartProductModel) {
  if (state.products.find(p => p._id === product._id)) {
    const newProducts = state.products.slice();
    const cartProduct = newProducts.find(p => p._id === product._id);
    cartProduct.quantity = +1;
    return {
      ...state,
      products: newProducts
    };
  }


  return {
    ...state,
    products: [...state.products, product]
  };
}

function updateCart(state: CartState, id: string, quantity: number) {
  // debugger
  const newProducts = state.products.slice();
  const cartProduct = newProducts.find(p => p._id === id);
  cartProduct.quantity = quantity;

  return {
    ...state,
    products: newProducts
  };
}

function removeFromCart(state: CartState, id: string) {
  return {
    ...state,
    products: [...state.products.filter(p => p._id !== id)]
  };
}

function clearCart(state) {
  return {
    ...state,
    products: []
  };
}

export function cartReducer(state: CartState = initialState, action) {
  switch (action.type) {
    case ADD_TO_CART:
      return addToCart(state, action.payload);

    case UPDATE_CART:
      return updateCart(state, action.id, action.quantity);

    case REMOVE_FROM_CART:
      return removeFromCart(state, action.id);

    case CLEAR_CART:
      return clearCart(state);
    default:
      return state;
  }
}
import ProductState from './product.state';
import * as ProductActions from './product.actions';

const initialState: ProductState = {
  all: []
};

function getAllProducts(state, action) {
  return {
    ...state,
    all: action
  };
}

function createProduct(state, action) {
  return {
    ...state,
    all: [...state.all, action]
  };
}

function editProduct(state, action) {
  return {
    ...state,
    all: [...state.all.filter(p => p._id !== action._id), action]
  };
}


export function productReducer(
  state: ProductState = initialState,
  action: ProductActions.Types
) {
  switch (action.type) {
    case ProductActions.GET_ALL_PRODUCTS:
      return getAllProducts(state, action.payload);

    case ProductActions.CREATE_PRODUCT:
      return createProduct(state, action.payload);

    case ProductActions.EDIT_PRODUCT:
      return editProduct(state, action.payload);


    default:
      return initialState;
  }
}
产品状态

    import ProductModel from '../../models/product/product.model';

export default interface ProductState {
  all: ProductModel[];
}
产品列表组件

import { Component, OnInit, Output, DoCheck } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ProductService } from 'src/app/core/services/product.service';
import { Store } from '@ngrx/store';
import { AppState } from 'src/app/core/store/app.state';
import { animations } from './product-list-animation';
import { Subscription } from 'rxjs';
import ProductModel from 'src/app/core/models/product/product.model';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
  animations: animations
})
export class ProductListComponent implements OnInit {
  @Output()
  products: ProductModel[];

  subscribe$: Subscription[] = [];

  protected pageSize: number = 6;
  currentPage: number = 1;
  constructor(
    private spinner: NgxSpinnerService,
    private productService: ProductService,
    private store: Store<AppState>
  ) {}

  ngOnInit() {
    this.spinner.show();
    this.productService.getAllProducts();

    this.subscribe$.push(
      this.store
        .select<ProductModel[]>(state => state.product.all)
        .subscribe(products => {
          this.products = products;
          this.spinner.hide();
        })
    );
  }

  changePage(page) {
    this.currentPage = page;
  }

  ngOnDestroy(): void {
    this.subscribe$.forEach(sub => sub.unsubscribe());
  }
}
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/core/services/auth.service';
import { Product } from 'src/app/models/product.model';
import { CartProductModel } from 'src/app/core/models/cart/cart.model';
import { Store } from '@ngrx/store';
import { AppState } from 'src/app/core/store/app.state';
import { AddToCart } from 'src/app/core/store/cart/cart.actions';
@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.scss']
})
export class CardComponent implements OnInit {
  @Input() product: Product;

  isAdmin: boolean = false;
  isInCart: boolean;
  route: Router;
  constructor(
    private authService: AuthService,
    private router: Router,
    private store: Store<AppState>
  ) {}

  ngDoCheck() {
    this.isAdmin = this.authService.getIsAdmin();
  }

  addToCart() {
    if (!this.authService.isAuth()) {
      this.router.navigate(['/']);
      return;
    }

    const productToAdd = new CartProductModel(
      this.product._id,
      this.product.name,
      this.product.image,
      this.product.price,
      1
    );

    console.log(productToAdd);
    this.store.dispatch(new AddToCart(productToAdd));
  }
  ngOnInit() {}
}
从'@angular/core'导入{Component,OnInit,Output,DoCheck};
从“ngx微调器”导入{NgxSpinnerService};
从'src/app/core/services/product.service'导入{ProductService};
从'@ngrx/Store'导入{Store};
从'src/app/core/store/app.state'导入{AppState};
从“/产品列表动画”导入{animations};
从“rxjs”导入{Subscription};
从“src/app/core/models/product/product.model”导入ProductModel;
@组成部分({
选择器:'应用程序产品列表',
templateUrl:'./product list.component.html',
样式URL:['./产品列表.component.scss'],
动画:动画
})
导出类ProductListComponent实现OnInit{
@输出()
产品:ProductModel[];;
订阅$:订阅[]=[];
受保护页面大小:数字=6;
当前页面:编号=1;
建造师(
私人微调器:NgxSpinnerService,
私人产品服务:产品服务,
私人商店
) {}
恩戈尼尼特(){
this.spinner.show();
this.productService.getAllProducts();
此。订阅$。推送(
这家商店
.select(state=>state.product.all)
.订阅(产品=>{
这一点。产品=产品;
this.spinner.hide();
})
);
}
更改页面(第页){
this.currentPage=第页;
}
ngOnDestroy():void{
this.subscribe$.forEach(sub=>sub.unsubscribe());
}
}
卡片组件

import { Component, OnInit, Output, DoCheck } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ProductService } from 'src/app/core/services/product.service';
import { Store } from '@ngrx/store';
import { AppState } from 'src/app/core/store/app.state';
import { animations } from './product-list-animation';
import { Subscription } from 'rxjs';
import ProductModel from 'src/app/core/models/product/product.model';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
  animations: animations
})
export class ProductListComponent implements OnInit {
  @Output()
  products: ProductModel[];

  subscribe$: Subscription[] = [];

  protected pageSize: number = 6;
  currentPage: number = 1;
  constructor(
    private spinner: NgxSpinnerService,
    private productService: ProductService,
    private store: Store<AppState>
  ) {}

  ngOnInit() {
    this.spinner.show();
    this.productService.getAllProducts();

    this.subscribe$.push(
      this.store
        .select<ProductModel[]>(state => state.product.all)
        .subscribe(products => {
          this.products = products;
          this.spinner.hide();
        })
    );
  }

  changePage(page) {
    this.currentPage = page;
  }

  ngOnDestroy(): void {
    this.subscribe$.forEach(sub => sub.unsubscribe());
  }
}
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/core/services/auth.service';
import { Product } from 'src/app/models/product.model';
import { CartProductModel } from 'src/app/core/models/cart/cart.model';
import { Store } from '@ngrx/store';
import { AppState } from 'src/app/core/store/app.state';
import { AddToCart } from 'src/app/core/store/cart/cart.actions';
@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.scss']
})
export class CardComponent implements OnInit {
  @Input() product: Product;

  isAdmin: boolean = false;
  isInCart: boolean;
  route: Router;
  constructor(
    private authService: AuthService,
    private router: Router,
    private store: Store<AppState>
  ) {}

  ngDoCheck() {
    this.isAdmin = this.authService.getIsAdmin();
  }

  addToCart() {
    if (!this.authService.isAuth()) {
      this.router.navigate(['/']);
      return;
    }

    const productToAdd = new CartProductModel(
      this.product._id,
      this.product.name,
      this.product.image,
      this.product.price,
      1
    );

    console.log(productToAdd);
    this.store.dispatch(new AddToCart(productToAdd));
  }
  ngOnInit() {}
}
从'@angular/core'导入{Component,OnInit,Input};
从'@angular/Router'导入{Router};
从'src/app/core/services/auth.service'导入{AuthService};
从'src/app/models/Product.model'导入{Product};
从'src/app/core/models/cart/cart.model'导入{CartProductModel};
从'@ngrx/Store'导入{Store};
从'src/app/core/store/app.state'导入{AppState};
从'src/app/core/store/cart/cart.actions'导入{AddToCart};
@组成部分({
选择器:“应用程序卡”,
templateUrl:“./card.component.html”,
样式URL:['./card.component.scss']
})
导出类CardComponent实现OnInit{
@输入()产品:产品;
isAdmin:boolean=false;
isInCart:布尔型;
路由:路由器;
建造师(
私有authService:authService,
专用路由器:路由器,
私人商店
) {}
ngDoCheck(){
this.isAdmin=this.authService.getIsAdmin();
}
addToCart(){
如果(!this.authService.isAuth()){
this.router.navigate(['/']);
回来
}
const productToAdd=新的CartProductModel(
此。产品。\u id,
此.product.name,
这个产品,这个形象,
这个,产品,价格,
1.
);
console.log(productToAdd);
this.store.dispatch(new AddToCart(productToAdd));
}
ngOnInit(){}
}

问题在于,在您的
productReducer
函数中,
开关盒中的
默认值
返回
初始状态
,而不是返回
状态

请向我们显示与已消失的集合的绑定。