NGXS状态管理:在调用操作时更改状态并将其保存到DB

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NGXS状态管理:在调用操作时更改状态并将其保存到DB相关的知识,希望对你有一定的参考价值。

我有几部电影,可以通过NGXS状态管理模式更新,删除和喜欢。

我想更新我的商店以显示是否喜欢电影并将状态保存在数据库中。

更新和删除操作工作,但类似的操作不起作用,我不明白为什么。它无法保存在DB中。如果有人可以帮助我,我就会被困住。下面是我的代码,谢谢。

db.json

"movies": [
{
  "id": 1,
  "title": "Avengers Infinity War",
  "imageUrl": "https://fakeimg.pl/600x600/000000/fff",
  "liked": (here I want to change the status to true or false when clicked)

},
{
  "id": 2,
  "title": "Avengers Endgame",
  "imageUrl": "https://fakeimg.pl/600x600/000000/fff"
}

]

Movie.ts

 export interface Movie {
 id: number;
 title: string;
 imageUrl: string;
 liked: boolean;
}

movie.action.ts

 export class UpdateMovie {
      static readonly type = '[Movie] UpdateMovie';
      constructor(public payload: Movie, public id: number) {}
    }

 export class DeleteMovie {
     static readonly type = '[Movie] DeleteMovie';
     constructor(public id: number) {}
    }

  export class LikeMovie {
      static readonly type = '[Movie] LikeMovie';
      constructor(public payload: Movie) {}
    }

电影service.ts

 updateMovie(payload: Movie, id: number) {
    return this.httpClient
     .put<Movie>(encodeURI(this.URL_BASE + `movies/${id}`), payload)
   }

deleteMovie(id: number) {
  return this.httpClient
    .delete(encodeURI(this.URL_BASE + `movies/${id}`))
  }

likeMovie(payload: Movie) {
    return this.httpClient
      .post<Movie>(encodeURI(this.URL_BASE + `movies`), payload);
   }

movie.state.ts

   export class MovieStateModel {
       movies: Movie[];
       selectedMovie: Movie;
       liked: Movie[];
     }

   @State<MovieStateModel>({
      name: 'movies',
      defaults: {
      movies: [],
      selectedMovie: null,
      liked: []
    }
  })

   @Action(DeleteMovie)
   deleteMovie({ getState, setState }: StateContext<MovieStateModel>, {id}: DeleteMovie) {
    return this.movieService.deleteMovie(id).pipe(tap(() => {
      const state = getState();
      setState({
        ...state,
        movies: state.movies.filter(item => item.id !== id)
      });
    }));
   }

 @Action(UpdateMovie)
 updateMovie({ getState, setState }: StateContext<MovieStateModel> {payload, id }: UpdateMovie) {
    return this.movieService.updateMovie(payload, id).pipe(tap((result) =>
  {
      const state = getState();
      const movieList = [...state.movies];
      const movieIndex = movieList.findIndex(item => item.id === id);
      movieList[movieIndex] = result;
      setState({
         ...state,
         movies: movieList
       });
     }));
    }

 @Action(LikeMovie)
 LikeMovie({ getState, setState }: StateContext<MovieStateModel>, {payload}: LikeMovie) {
    return this.movieService.likeMovie(payload).pipe(tap(() => {
      const state = getState();
      setState({
         ...state,
         liked: [...state.liked, payload]
      });
    }));
  }

电影list.component.ts

  likeMovie(payload: Movie) {
  this.store.dispatch(new LikeMovie(payload));
}
答案

欢迎来到StackOverflow :)

除了服务器错误(Christian已在评论中提到),似乎在处理LikeMovie操作时存在一个小错误。

如果你的liked属性是boolean,那么你应该确保为它分配了一个布尔值。

setState({
  ...state,
  liked: [...state.liked, payload] <-- assigns an array
});

正确的方法是:

setState({
  ...state,
  liked: payload
});
另一答案

好的,所以我做了一些测试,我已经删除了对DB的请求,使其变得简单。

基于我的电影模型,我想在调用liked时将电影的Like action属性更新为true或false,而是创建一个名为liked的新状态,其中包含电影......我知道我正在做某事错了,我在官方文件中找不到合适的答案,而且我是NGXS的新手。

以下是我的文件:

Movie.ts

export interface Movie {
  id: number;
  title: string;
  imageUrl: string;
  liked: boolean;
}

movie.states.ts

export class MovieStateModel {
  movies: Movie[];
  selectedMovie: Movie;
}

@State<MovieStateModel>({
  name: 'movies',
  defaults: {
    movies: [],
    selectedMovie: null
  }
})

@Action(LikeMovie)
  LikeMovie({ getState, setState }: StateContext<MovieStateModel>, { payload }: LikeMovie) {
    const state = getState();
    setState({
      ...state,
      liked: payload
    });
  }

movie.actions.ts

export class LikeMovie {
  static readonly type = '[Movie] LikeMovie';

  constructor(public payload: Movie) {}
}

电影list.component.ts

likeMovie(payload: Movie) {
    this.store.dispatch(new LikeMovie(payload));
  }

以上是关于NGXS状态管理:在调用操作时更改状态并将其保存到DB的主要内容,如果未能解决你的问题,请参考以下文章

ngxs:在 Action 中访问不同的状态

NGXS调度为状态运行所有操作

ngrx 和 ngxs 之间的性能差异? [关闭]

调度操作后 Redux 状态未更新

ngxs、redux 开发工具显示之前的状态

在ngxs中重置状态