【发布时间】:2020-04-07 19:22:21
【问题描述】:
我第一次使用 Ngrx,虽然它相对简单,但在调度状态时出现错误。当用户打开应用程序时,他需要输入他的姓名并提交,下一个屏幕应该显示“问候{{用户名}}”。用户提交后,我收到此错误--> core.js:6014 ERROR TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
感谢您的帮助
import { Action } from '@ngrx/store';
import { UserName, WishListItem } from 'src/model/name.model';
export enum AddToStateActionType{
ADD_NAME = '[ADD_NAME] add name',
ADD_TO_WISHLIST = '[ADD_TO_WISHLIST] add to wishlist'
}
export class AddWelcomeNameAction implements Action {
readonly type = AddToStateActionType.ADD_NAME;
constructor(public payload: UserName){}
}
export class AddToWishList implements Action {
readonly type = AddToStateActionType.ADD_TO_WISHLIST;
constructor(public payload: WishListItem){}
}
export type UserAction = AddWelcomeNameAction | AddToWishList ;
<!--Reducer-->
import {AddToStateActionType, UserAction} from './../action/action';
import { UserName, WishListItem } from 'src/model/name.model';
const initialState: any = {
name: '',
wishlist: []
};
export function reducer(state: any = initialState, action: any) {
switch(action.type) {
case AddToStateActionType.ADD_NAME:
return [...state, action.payload.name];
case AddToStateActionType.ADD_TO_WISHLIST:
return [...state. action.payload.wishlist];
default:
return state;
}
}
<!--AppState-->
import { UserName, WishListItem } from 'src/model/name.model';
export interface AppState {
readonly username: UserName;
readonly wishlist: Array<WishListItem> ;
}
<!--Welcome component-->
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Store } from '@ngrx/store';
import { AppState } from '../app.state/app.state';
import * as Actions from '../../action/action';
import {Router} from '@angular/router';
import { UserName } from 'src/model/name.model';
@Component({
selector: 'app-welcome',
templateUrl: './welcome.component.html',
styleUrls: ['./welcome.component.css']
})
export class WelcomeComponent implements OnInit {
userName: UserName = {name: ''};
profileForm = new FormGroup({
userName: new FormControl(''),
});
constructor(private store: Store<AppState>, private router: Router) { }
ngOnInit() {
}
onSubmit() {
this.store.dispatch(new Actions.AddWelcomeNameAction({name: this.profileForm.value}));
this.router.navigate(['/search']);
}
}
【问题讨论】:
-
看起来像扩展运算符
...中的问题你可以在减速器返回之前添加console.log(state)吗?你能看到什么? -
返回空状态:{name: "", wishlist: Array(0)}
标签: angular ngrx ngrx-store