Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.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 是否在服务器调用后更新状态?_Javascript_Angular_Typescript_Ngrx - Fatal编程技术网

Javascript 是否在服务器调用后更新状态?

Javascript 是否在服务器调用后更新状态?,javascript,angular,typescript,ngrx,Javascript,Angular,Typescript,Ngrx,在从服务器接收到一组新数据后,我对更新和从reducer返回正确的状态感到困惑。实际上,我不明白在服务器响应之后返回什么(如何更新状态)。 为了更清楚地了解我的困惑: 例如:在todo应用程序上,我会有一个减速机: // imports.. export function todoReducer(state = [], action) { switch (action.type) { // some cases... case todoActions.

在从服务器接收到一组新数据后,我对更新和从reducer返回正确的状态感到困惑。实际上,我不明白在服务器响应之后返回什么(如何更新状态)。 为了更清楚地了解我的困惑:

例如:在todo应用程序上,我会有一个减速机:

// imports..

export function todoReducer(state = [], action) {
    switch (action.type) {
        // some cases...

        case todoActions.TODO_LOADED: {
            return [
                ...state,
                {
                ...action.payload   
                } 
            ]    
        }

        // some more cases...
        default: 
           return state; 
    }
}
以及影响:

@Effect() todoList$: Observable<any> = this.action$
        .ofType(todoActions.TODO_LOAD)
        .switchMap(() => {
            return this.http
            .get('/rest/todo-list')
            .map((todos: Todos) => new todoActions.TodoLoaded(todos))
            .catch(err => Observable.of(new todoActions.TodoFailed(err)));
        });
这是反模式吗

也许这是个愚蠢的问题,但我不明白


提前谢谢

我会尝试一种更标准、更干净、更简单的解决方案。还将解决您的副本问题,并始终正确更新您的存储

你需要6个动作:

import { Action } from '@ngrx/store';

/* App Models */
import { Todo } from './todo.model';

export const TODO_GET = '[Todo] get todo';
export const TODO_GET_SUCCESS = '[Todo] get todo success';
export const TODO_DELETE = '[Todo] delete todo';
export const TODO_DELETE_SUCCESS = '[Todo] delete todo success';
export const TODO_GET_BY_ID = '[Todo] get todo by id';
export const TODO_GET_BY_ID_SUCCESS = '[Todo] get todo by id success';

// Gets Todos from APIs
export class TodoGetAction implements Action {
  readonly type = TODO_GET;
}

// Returns APIs fetched Todos
export class TodoGetSuccessAction implements Action {
  readonly type = TODO_GET_SUCCESS;
  constructor(public payload: Todo[]) {}
}

// Deletes a Todo given its string id
export class TodoDeleteAction implements Action {
  readonly type = TODO_DELETE;
  constructor(public payload: string) {}
}

// True -> Success, False -> Error
export class TodoDeleteSuccessAction implements Action {
  readonly type = TODO_DELETE_SUCCESS;
  constructor(public payload: Todo[]) {}
}

// Takes the id of the todo
export class TodoGetByIdAction implements Action {
  readonly type = TODO_GET_BY_ID;
  constructor(public payload: string) {}
}

// Returns todo by id
export class TodoGetByIdSuccessAction implements Action {
  readonly type = TODO_GET_BY_ID_SUccess;
  constructor(public payload: Todo) {}
}

export type All =
  | TodoGetAction
  | TodoGetSuccessAction
  | TodoDeleteAction
  | TodoDeleteSuccessAction
  | TodoGetByIdAction
  | TodoGetByIdSuccessAction;
然后,您将拥有一个具有简单状态的reducer,该状态具有一个todo数组和一个由id选择的当前todo。我们在这里处理所有成功操作,而在效果中处理所有正常操作:

import { createFeatureSelector } from '@ngrx/store';
import { createSelector } from '@ngrx/store';

/* ngrx */
import * as TodoActions from './todo.actions';

/* App Models */
import { Todo } from './todo.model';

// Get all actions
export type Action = TodoActions.All;

export interface TodoState {
  todos: Todo[];
  todoById: Todo;
}

// Initial state with empty todos array
export const todoInitialState: TodoState = {
   todos: [],
   todoById: new Todo({})
}

/* Selectors */
export const selectTodoState = createFeatureSelector<
  TodoState
>('todo');
// Select all Todos
export const selectTodos = createSelector(
  selectTodoState,
  (state: TodoState) => state.todos
);
export const selectTodoByID = createSelector(
  selectTodoState,
  (state: TodoState) => state.todoById
);

export function todoReducer(
  state: TodoState = todoInitialState,
  action: Action
) {
  switch (action.type) {
    case TodoActions.TODO_GET_SUCCESS:
      const oldTodos = state.todos;
      // Add new todos to old ones
      const newTodos = oldTodos.concat(action.payload);
      // Cast to set to have only unique todos
      const uniqueTodos = new Set(newTodos);
      // Cast back to array to get an array out of the set
      const finalTodos = Array.from(uniqueTodos);
      return {
         ...state,
         todos: [...finalTodos]
      }
    case TodoActions.TODO_DELETE_SUCCESS:
       return {
         ...state,
         todos: state.todos.filter( todo => return todo.id !== action.payload)
       }
     case TodoActions.TODO_GET_BY_ID_SUCCESS:
       return {
         ...state,
         todoById: state.todos.filter( todo => return todo.id === action.payload)[0]
       }
     default: 
       return state; 
  }
}

我想说的是,您正在正确的轨道上进行成功(或失败)删除操作:)感谢您的示例!然而通过deleteTodo$effect,它删除客户端上的todo,但不删除数据库中的todo(无http req)。我的问题都是关于这个。当您调用后端以删除todo时,您如何在客户端上更新它。与您为获取项目所做的处理相同。分派
deleteTodo
,它将
DELETE/todo/{id}
传递字符串id给它。按您的效果调用
todoService
。如果后端响应成功,只需使用
deletetetodosucess
从存储中删除todo即可。我不知道你的后端会返回什么,但会是这样的。
import { Action } from '@ngrx/store';

/* App Models */
import { Todo } from './todo.model';

export const TODO_GET = '[Todo] get todo';
export const TODO_GET_SUCCESS = '[Todo] get todo success';
export const TODO_DELETE = '[Todo] delete todo';
export const TODO_DELETE_SUCCESS = '[Todo] delete todo success';
export const TODO_GET_BY_ID = '[Todo] get todo by id';
export const TODO_GET_BY_ID_SUCCESS = '[Todo] get todo by id success';

// Gets Todos from APIs
export class TodoGetAction implements Action {
  readonly type = TODO_GET;
}

// Returns APIs fetched Todos
export class TodoGetSuccessAction implements Action {
  readonly type = TODO_GET_SUCCESS;
  constructor(public payload: Todo[]) {}
}

// Deletes a Todo given its string id
export class TodoDeleteAction implements Action {
  readonly type = TODO_DELETE;
  constructor(public payload: string) {}
}

// True -> Success, False -> Error
export class TodoDeleteSuccessAction implements Action {
  readonly type = TODO_DELETE_SUCCESS;
  constructor(public payload: Todo[]) {}
}

// Takes the id of the todo
export class TodoGetByIdAction implements Action {
  readonly type = TODO_GET_BY_ID;
  constructor(public payload: string) {}
}

// Returns todo by id
export class TodoGetByIdSuccessAction implements Action {
  readonly type = TODO_GET_BY_ID_SUccess;
  constructor(public payload: Todo) {}
}

export type All =
  | TodoGetAction
  | TodoGetSuccessAction
  | TodoDeleteAction
  | TodoDeleteSuccessAction
  | TodoGetByIdAction
  | TodoGetByIdSuccessAction;
import { createFeatureSelector } from '@ngrx/store';
import { createSelector } from '@ngrx/store';

/* ngrx */
import * as TodoActions from './todo.actions';

/* App Models */
import { Todo } from './todo.model';

// Get all actions
export type Action = TodoActions.All;

export interface TodoState {
  todos: Todo[];
  todoById: Todo;
}

// Initial state with empty todos array
export const todoInitialState: TodoState = {
   todos: [],
   todoById: new Todo({})
}

/* Selectors */
export const selectTodoState = createFeatureSelector<
  TodoState
>('todo');
// Select all Todos
export const selectTodos = createSelector(
  selectTodoState,
  (state: TodoState) => state.todos
);
export const selectTodoByID = createSelector(
  selectTodoState,
  (state: TodoState) => state.todoById
);

export function todoReducer(
  state: TodoState = todoInitialState,
  action: Action
) {
  switch (action.type) {
    case TodoActions.TODO_GET_SUCCESS:
      const oldTodos = state.todos;
      // Add new todos to old ones
      const newTodos = oldTodos.concat(action.payload);
      // Cast to set to have only unique todos
      const uniqueTodos = new Set(newTodos);
      // Cast back to array to get an array out of the set
      const finalTodos = Array.from(uniqueTodos);
      return {
         ...state,
         todos: [...finalTodos]
      }
    case TodoActions.TODO_DELETE_SUCCESS:
       return {
         ...state,
         todos: state.todos.filter( todo => return todo.id !== action.payload)
       }
     case TodoActions.TODO_GET_BY_ID_SUCCESS:
       return {
         ...state,
         todoById: state.todos.filter( todo => return todo.id === action.payload)[0]
       }
     default: 
       return state; 
  }
}
import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { Store } from '@ngrx/store';

/** rxjs **/
import { mergeMap } from 'rxjs/operators/mergeMap';
import { catchError } from 'rxjs/operators/catchError';
import { map } from 'rxjs/operators/map';
import { of } from 'rxjs/observable/of';

/** ngrx **/
import * as TodoActions from './todo.actions';
import { AppState } from '../app-state.interface';

/** App Services **/
import { TodoService } from './province.service';

@Injectable()
export class TodoEffects {

  @Effect()
  getTodos$ = this.actions$.ofType(TodoActions.TODO_GET).pipe(
    mergeMap(() => {
      // I Imagine you can move your api call in such service
      return this.todoService.getTodos().pipe(
        map((todos: Todo[]) => {
          return new TodoActions.TodoGetSuccessAction(todos);
        }),
        catchError((error: Error) => {
          return of(// Handle Error Here);
        })
      );
    })
  );

  @Effect()
  deleteTodo$ = this.actions$.ofType(TodoActions.TODO_DELETE).pipe(
    mergeMap((action) => {
        return new TodoActions.TodoDeleteSuccessAction(action.payload);
    })
  );

  @Effect()
  getTodoByID$ = this.actions$.ofType(TodoActions.TODO_GET_BY_ID).pipe(
    mergeMap((action) => {
        return new TodoActions.TodoGetByIdSuccessAction(action.payload);
    })
  );

  constructor(
    private todoService: TodoService,
    private actions$: Actions,
    private store: Store<AppState>
  ) {}
}
. . .

todos$: Observable<Todo[]>;
todoById$: Observable<Todo>;

constructor(private store: Store<AppState>) {
    this.todos$ = this.store.select(selectTodos);
    this.todo$ = this.store.select(selectTodoById);
}

ngOnInit() {
    this.store.dispatch(new TodoActions.TodoGetAction);
}