简体   繁体   English

NgRX实体:ID在州内未定义

[英]NgRX Entity : ids are undefined in the State

I've been trying @ngrx/entity in a dummy "Todo" project, with a single AppModule, a single reducer and a single component. 我一直在虚拟的“Todo”项目中尝试@ ngrx / entity,只有一个AppModule,一个减速器和一个组件。 However, I am having issues trying it out. 但是,我在试用它时遇到了问题。

My actions are pretty straight forward, just some CRUD operations : 我的行为很简单,只是一些CRUD操作:

import { Action } from '@ngrx/store';
import { Todo }  from '../../models/todo';


export const CREATE = '[Todo] Create'
export const UPDATE = '[Todo] Update'
export const DELETE = '[Todo] Delete'

export class Create implements Action {
    readonly type = CREATE;
    constructor(public todo: Todo) { }
}

export class Update implements Action {
    readonly type = UPDATE;
    constructor(
        public id: string,
        public changes: Partial<Todo>,
      ) { }
}

export class Delete implements Action {
    readonly type = DELETE;
    constructor(public id: string) { }
}

export type TodoActions
= Create
| Update
| Delete;

Then my reducer file contains everything I need to handle my entity : 然后我的reducer文件包含处理我的实体所需的一切:

import * as actions from './todo.actions';
import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { createFeatureSelector } from '@ngrx/store';
import { Todo } from '../../models/todo';

export interface TodosState extends EntityState<Todo> {}
export const todoAdapter = createEntityAdapter<Todo>();

export const initialState: TodosState = todoAdapter.getInitialState();

export function todoReducer(state: TodosState = initialState, action: actions.TodoActions) {
    console.log("Got new action", action);
    switch(action.type) {
        case actions.CREATE:
            return todoAdapter.addOne(action.todo, state);
        case actions.UPDATE:
            return todoAdapter.updateOne({
                id: action.id,
                changes: action.changes
            }, state);
        case actions.DELETE:
            return todoAdapter.removeOne(action.id, state);
        default:
            return state;
    }
}

export const {
    selectIds,
    selectEntities,
    selectAll,
    selectTotal
} = todoAdapter.getSelectors();

In my app.module.ts file, I am doing the following : 在我的app.module.ts文件中,我正在执行以下操作:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

import { AppComponent } from './app.component';
import { todoReducer } from './reducers/todo.reducer';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    StoreModule.forRoot({
      todo: todoReducer
    }),
    StoreDevtoolsModule.instrument({maxAge: 25}),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Finally, in my app.component.ts , I am simply trying to create two TODOs : 最后,在我的app.component.ts ,我只是想创建两个TODO:

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';

import * as fromTodo from './reducers/todo.reducer';
import { Todo } from '../models/todo';
import { Create } from './reducers/todo.actions';


@Component({
    selector: 'app-root',
    template: `
    `,
    styles: []
})
export class AppComponent implements OnInit {

    public todos: Observable<Todo[]>;


    constructor(private store: Store<fromTodo.TodosState>) {
        this.store.dispatch(new Create({
            title: "Test todo",
            content: "This is a test todo",
            date: new Date()
        }))
        this.store.dispatch(new Create({
            title: "Test todo 2",
            content: "This is another todo",
            date: new Date()
        }))
    }

    ngOnInit() {
        this.todos = this.store.select(fromTodo.selectAll);
    }

}

However, after running this, I inspected the Redux DevTools . 然而,在运行之后,我检查了Redux DevTools I saw that it only creates the first TODO, and its id is "undefined". 我看到它只创建了第一个TODO,它的id是“未定义的”。

运行应用程序并分派两个事件后的应用程序状态

My console.log in my reducer displays @ngrx/store/init , as well as both [TODO] Create actions 我的reducer中的console.log显示@ngrx/store/init ,以及[TODO]创建操作

Moreover, if I try to ngFor | async 而且,如果我尝试ngFor | async ngFor | async through my todos in my component, I get various errors depending on what I try ("Cannot read 'map' property of undefined" mainly). 通过我的组件中的todos ngFor | async ,我会根据我的尝试得到各种错误(主要是“无法读取'未定义的'map'属性)。

After some research, I noticed that @ngrx/entity uses the id property of the model you use. 经过一些研究,我注意到@ngrx/entity使用你使用的模型的id属性。 In my case, my Todo model did not have any id property, so @ngrx/entity could not handle my entities. 在我的情况下,我的Todo模型没有任何id属性,所以@ngrx/entity无法处理我的实体。 I thought it generated ids internally, but apparently it doesn't. 我认为它在内部生成了ids,但显然它没有。

So the fix to this issue is to add an id property to the model, and auto-generate it each time you add an item to the state. 因此,解决此问题的方法是向模型添加id属性,并在每次向项目添加项目时自动生成它。

There is a Angular2 UUID module for example. 例如,有一个Angular2 UUID模块。

In my case, I am using ngrx with AngularFire2 , which has a createId() method : const id = this.afs.createId() . 在我的例子中,我使用的ngrx带有AngularFire2 ,它有一个createId()方法: const id = this.afs.createId() Then I can add it to the item I want to add, and then store it in my Firestore database. 然后我可以将它添加到我想要添加的项目,然后将其存储在我的Firestore数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM