首页 > 解决方案 > 无法在 NGRX 效果元组错误中获取状态

问题描述

我正在尝试访问效果中的当前商店状态,以便我可以在本地存储我当前的购物车。我遵循了文档,但我不断收到 TS 错误。以下是我的影响及其引发的错误。我不确定是什么导致了这里的问题,因为我不熟悉该错误。

src/app/cart/store/cart.effects.ts(15,42) 中的错误:错误 TS2493:长度为“2”的元组类型“[never,ProductInterface[]]”在索引“2”处没有元素。[ng] src/app/cart/store/cart.effects.ts(15,54):错误 TS2493:长度为“2”的元组类型“[never,ProductInterface[]]”在索引“3”处没有元素。

import {Injectable} from '@angular/core';
import {Actions, createEffect, ofType} from '@ngrx/effects';
import {Store, select} from '@ngrx/store';
import {ProductInterface} from '../../interfaces/product.interface';
import {of} from 'rxjs'
import {CartActions, addToCart, clearCart, removeFromCart, updateCartQuantity, } from './cart.actions';
import {withLatestFrom, switchMap} from 'rxjs/operators';
import {Storage} from '@ionic/storage';
@Injectable()
export class CartEffects {

    storeCart$ = createEffect(() => this.actions$.pipe(
        ofType('[Cart Component] Add To Cart'),
        withLatestFrom(this.store.pipe(select('cart'))),
        switchMap(([action: CartActions, storeState: ProductInterface[]]) => {
            this.storage.set('cart', storeState);
            return of(action)
        })))

    constructor(
        private actions$: Actions,
        private storage: Storage,
        private store: Store<{cart: ProductInterface[]}>
    ) {}
}

标签: angularngrx

解决方案


您的代码的问题是您不能在元组中拥有类型(内部switchMap函数的函数参数)。尝试:

switchMap(([action, storeState]: [CartActions, ProductInterface[]]) => {})

推荐阅读