首页 > 解决方案 > “可观察”类型上不存在属性“价格”ngrx

问题描述

我正在尝试显示具有名称和价格属性的初始愿望清单状态。我收到“属性 'Price' 在类型 'Observable<wishlist[]>” 上不存在错误,但价格确实存在于愿望清单界面和减速器中。

稍后我将从我的产品列表中将产品添加到愿望清单,但我想首先让初始状态工作。

也许我在 html 中显示错误?错误地使用 for 循环。我不知道。

任何帮助表示赞赏。

继承人愿望清单界面

export interface wishlist{
    name: string; 
    Price: string; 

}

行动

import { Injectable } from '@angular/core'
import { Action } from '@ngrx/store'
import { wishlist } from 'model/wishlist.model'

export const ADD_WISHLIST   = '[WISHLIST] Add'
export const REMOVE_WISHLIST   = '[WISHLIST] Remove'


export class  AddWishlist implements Action{

    readonly type = ADD_WISHLIST


    //creating a class for each of the actions
    constructor(public payload: wishlist) {}
}

export class  RemoveWishlist implements Action{

    readonly type = REMOVE_WISHLIST


    //creating a class for each of the actions
    constructor(public payload: number) {}
}

export type Actions = AddWishlist | RemoveWishlist

减速器

import { Action, ActionsSubject } from '@ngrx/store'
import { wishlist } from 'model/wishlist.model'
//import { n } from 'node:inspector'
import * as WishlistActions from 'src/app/actions/wishlist.actions'

const initialState: wishlist ={
    name: 'insital wishlist',
    Price: '400'
}

export function wishlistreducer(state : wishlist[] = [initialState], action: WishlistActions.Actions){


    switch(action.type){
        case WishlistActions.ADD_WISHLIST: 
        return [...state, action.payload]; 

        default: 
        return state; 
    }
}

应用状态

import { wishlist } from 'model/wishlist.model';

export interface AppState{
    readonly WishList: wishlist[];
}`

愿望清单 html(这称为购物车,但我将其用作愿望清单)

<div class="right">

    <h3>Wishlist</h3>
    <ul>
        <li *ngFor ="let wishlist of wishlists | async"></li>
        <a>{{ wishlists.Price }}</a>
    </ul>


</div>

愿望清单 component.ts (它被称为购物车不介意)

import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { wishlist } from 'model/wishlist.model';
import { AppState } from 'src/app/app.state';


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


wishlists: Observable<wishlist[]>; 


  constructor( private store: Store<AppState>) {

    this.wishlists = store.select('WishList')


   }

  ngOnInit(): void {

 
  }
}

标签: angularngrx

解决方案


为了详细说明我的评论,您错误地使用了循环。*ngFor 循环正在解包您的数组并将每个值(迭代)分配给变量“wishlist”。因此,您需要在访问属性价格时使用此变量。当前,您正在尝试访问Price从商店返回的 observable 上的属性。

 <ul>
      <li *ngFor ="let wishlist of wishlists | async">
            <a>{{ wishlist.Price }}</a>
      </li>      
 </ul>

推荐阅读