javascript - Angular 8 使用 NgRx 从 http 设置状态

标签 javascript angular typescript redux ngrx

我的目标:使用“NgRx”做事方式更新我的服务文件。

我正在发出 GET 请求以从我的服务中获取菜单数据,一旦该调用发生,我希望它在 NgRx 中设置我的“菜单”状态,以便我可以在任何地方访问菜单数据。

我不确定解决此问题的最佳方法是什么。

我当前的代码:

Menu.service.ts

  constructor(private http: HttpClient, private store: Store<fromApp.AppState>) { }

  public getMenu(): Observable<Restaurant> {
    // not sure where to run this code:
    // this.store.dispatch(new MenuActions.SetMenu(menu));

    return this.http.get<Menu>('http://localhost:1234/api/menu');
  }

问题:

1.) 在我的服务中发送菜单项是最佳做法吗?

2.) 在调用发送更新后,我是否应该使用“管道”运算符?

3.) 如果我使用 NgRx,我觉得我不需要订阅 getMenu(),因为状态将在这个文件中设置,我可以直接访问说明我通常会在哪里订阅这项服务。在这里使用服务文件有效,还是我对 ngrx 采取了错误的方法?如果这不正确,还有什么选择?

谢谢!

最佳答案

Is it best practice to dispatch the menu item in my service?

你可以,但我不推荐,因为 NGRX 对此有影响。 Effect代表副作用做一些逻辑计算。

Should I use the 'pipe' operator after the call is made to dispatch the update?

你不应该。

If I'm using NgRx, I feel like I don't need to subscribe to getMenu(), since the state will be set in this file, and I can just access state where I'd normally subscribe to this service. Is using the service file here valid, or am I taking the wrong approach for ngrx? If this isn't correct, what is the alternative?

你不应该。而是在您的组件中像这样订阅

例子

我有这样的服务

  getPosts(): Observable<any> {
    return this.http.get("https://jsonplaceholder.typicode.com/posts");
  }

然后我调用api的效果

 getPosts$ = createEffect(() =>
    this.actions$.pipe(
      ofType(PostActions.LoadPosts),
      switchMap(_ => {
        return this.postService
          .getPosts()
          .pipe(
            map(
              (posts: IPost[]) => PostActions.LoadPostsSuccess({ posts }),
              catchError(errors => of(PostActions.LoadPostsFail(errors)))
            )
          );
      })
    )
  );

所以在我的容器组件中

  public posts$: Observable<IPost[]>;

  constructor(private store: Store<PostState>) {}

  ngOnInit() {
    this.store.dispatch(LoadPosts());
    this.posts$ = this.store.pipe(select(selectAllPosts));
  }

<div class="row">
  <div class="col-3" *ngFor="let post of posts$ | async">
    <div class="card card-container">
      <div class="card-body">
        <h5 class="card-title">{{ post.title }}</h5>
        <p class="card-text">{{ post.body }}</p>
        <a
          class="btn btn-outline-primary"
          [routerLink]="['/posts/',post.id]"
          role="button"
          >Go to detail</a
        >
      </div>
    </div>
  </div>
</div>

当然你需要选择器来获取组件中的数据

export const selectPostState = createFeatureSelector<PostState>(
  POST_FEATURE.storekey
);

export const selectPostsEntities = createSelector(
  selectPostState,
  posts => posts.entities //object look up
);

export const selectAllPosts = createSelector(
  selectPostsEntities,
  posts => Object.keys(posts).map(key => posts[key]) // use *ngFor
);

关于javascript - Angular 8 使用 NgRx 从 http 设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318224/

相关文章:

javascript - 为什么 Redux 将我的正则表达式值保存为对象类型

javascript - 调用 laravel {{action(Controller@method}} 并从 vue.js 数组传递变量

当图像不存在时,Angular universal/ng-toolkit/universal 会抛出错误

types - 为什么 Typescript 不能推断这个函数的参数类型?

javascript - 通过唯一关键字分隔 JavaScript 数组

javascript - JQuery - 动态创建的元素 css 不起作用

angular - 如何从 Visual Studio 2015 中的非相对路径导入模块

javascript - Angular 不在控制台上显示 JavaScript 错误

node.js - 默认的 Firebase 应用不存在。确保在使用任何 Firebase 服务之前调用 initializeApp()。在 FirebaseAppError

Angular 2 阅读更多指令