首页 > 解决方案 > 从 NGRX 存储中检索数据并触发新操作

问题描述

尽管我在 AngularJS 世界中花费了很多时间,在 Angular 世界中也花了一些时间,但我对 RXJS 和 NGRX 还很陌生,并且遇到了一些问题。我的 NGRX 设置类似于 NGRX 团队在他们的示例项目 ( https://stackblitz.com/run ) 中推荐的设置方式。

情况

我有一个名为“站点”的实体,已存储在我的 NGRX 商店中。当我到达特定屏幕时,我试图从我的商店获取“站点”的“ID”,然后使用站点 ID 作为参数发送一个新的 NGRX 操作。为此,我尝试订阅一个可观察的 site$ 并在该订阅中调度操作。

import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import * as fromSite from '../../site/store/reducers/site.reducer';
import * as SiteActions from '../../site/store/actions/site.actions';
import { Site } from '../../site/site';

@Component({
  selector: 'app-category-grouping',
  templateUrl: './category-grouping.component.html',
  styleUrls: ['./category-grouping.component.scss']
})
export class CategoryGroupingComponent implements OnInit {
  site$: Observable<any>;
  site: Site;

  constructor(private store: Store<fromSite.State>) {
    this.site$ = this.store.pipe(select(fromSite.getSite));
    this.site$.subscribe(data => {
      if (data && data.site) {
        this.store.dispatch(new SiteActions.GetGroupsAndCategories(data.site.id));
        this.site = data.site;
      }
    });
}

  ngOnInit() {}

}

问题

在订阅中调度操作(一旦我有了站点 ID)会破坏一切!浏览器完全冻结,必须强制退出。我没有收到任何控制台错误,但我一定是做错了什么。

问题

这样做的正确方法是什么?我不应该在订阅中这样做吗?有没有更好的方法从 store 中获取一个值,然后使用该值来调度另一个动作?

标签: angularrxjsstorengrx

解决方案


看起来你有递归:调度GetGroupsAndCategories动作改变输出select(fromSite.getSite)site$发出新值。

如果您想在导航到屏幕之前获取一些数据 - 使用解析器

@Injectable()
export class SomethingResolver implements Resolve<Action> {

  constructor (
    private store: Store<State>,
    private action$: Actions
  ) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Action> {
    this.store.dispatch({ type: Actions.FETCH_SOMETHING });
    const responseOK = this.action$.ofType(Actions.RESPONSE_OK);
    const responseError = this.action$.ofType(Actions.RESPONSE_ERROR)
      .do(() => this.router.navigate(['']);
    return Observable.race(responseOk, responseError).take(1);
  }
}

推荐阅读