簡體   English   中英

Angular 8 使用 NgRx 從 http 設置狀態

[英]Angular 8 set state from http with NgRx

我的目標:用“NgRx”的做事方式更新我的服務文件。

我正在發出 GET 請求以從我的服務中獲取菜單數據,一旦該調用發生,我希望它在 NgRx 中設置我的“菜單”狀態,以便我可以在任何地方訪問菜單數據。

我不確定解決這個問題的最佳方法是什么。

我目前的代碼:

菜單.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 采取了錯誤的方法? 如果這不正確,有什么替代方法?

謝謝!

在我的服務中調度菜單項是最佳實踐嗎?

你可以,但我不會推薦,因為 NGRX 對此有影響。 Effect 代表副作用做一些邏輯計算。

在調用發送更新后,我應該使用“管道”運算符嗎?

你不應該。

如果我使用 NgRx,我覺得我不需要訂閱 getMenu(),因為狀態將在這個文件中設置,我可以訪問我通常訂閱此服務的狀態。 在這里使用服務文件是否有效,還是我對 ngrx 采取了錯誤的方法? 如果這不正確,有什么替代方法?

你不應該。 而是在您的組件中像這樣訂閱

例子

我有這樣的服務

  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
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM