angular - 在路由解析器中调度 ngrx 存储操作

标签 angular redux ngrx ngrx-store

我目前有一个容器(有状态)组件,它调度 selectget基于 ngOnInit 中的路由参数 (id) 的操作方法。这些操作的重点是在我的商店中拥有数据和选定的 id。

我很好奇在解析器中调度这些 Action 是否正确?

感谢您的回复。

我的组件:

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  styleUrls: ['./container.component.css']
})
export class ContainerComponent implements OnInit, OnDestroy {

  private componetDestroyed$ = new Subject();

  constructor(private store: Store<fromRoot.State>, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params
      .filter(params => params['id'])
      .map(params => params['id'])
      .takeUntil(this.componetDestroyed$)
      .subscribe(id => {
        this.store.dispatch(new GetAction(id));
        this.store.dispatch(new SelectAction(id));
      });
  }

  ngOnDestroy() {
    this.componetDestroyed$.next();
    this.componetDestroyed$.unsubscribe();
  }   
}

我的路线:
[{
  path: ':id',
  component: ContainerComponent
}]

解析器将是:
@Injectable()
class MyResolver implements Resolve<any> {

constructor(private store: Store<fromRoot.State>) {}

resolve(route: ActivatedRouteSnapshot, state: RouteStateSnapshot) {
  let id = route.params['id'];
  this.store.dispatch(new SelectAction(id));
  this.store.dispatch(new GetAction(id));
  return null;
}

以及修改后的路线:
[{
  path: ':id',
  component: ContainerComponent,
  resolve: {
    store: MyResolver
  }
}]

这就是为什么我不确定这是正确的,因为商店将永远是 null .

最佳答案

您在 ngOnInit 中调度操作的方式没有任何问题基于 this.route.params .

重要的是解析器是路由的数据提供者。如果你不提供数据,那么你就错误地使用了它们。

在您的情况下,它听起来更像 canActivate负责发出 Action 并允许路由的守卫。

不过,您可以将解析器扩展到选择您想要的数据。

@Injectable({
    providedIn: 'root',
})
export class DataResolver implements Resolve<number> {
    constructor(private store: Store) {
    }

    public resolve(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<any> {
        this.store.dispatch(LoadDataForMyRoute());

        return this.store.pipe(
            select(dataForMyRoute),
            filter(data => !!data), // <- waiting until data is present
            take(1), // <- important to add
        );
    }
}

在您的组件中,您可以像那样访问它而不是 this.store.select .

constructor(
    protected readonly store: Store,
    protected readonly activatedRoute: ActivatedRoute,
) {}

public ngOnInit(): void {
    this.activatedRoute.data.subscribe(data => {
        // everything is here.
    });
}

关于angular - 在路由解析器中调度 ngrx 存储操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43982816/

相关文章:

angular - 是否需要根据 fromEvent 取消订阅事件

javascript - 当我看不到 api 结果时,我需要显示未找到数据

reactjs - 避免使用react-redux重新渲染一个大的项目列表

redux - 如何使用 ngFor 以角度获取和显示 ngrx 存储数据

angular - ngrx - createSelector 与 Observable.combineLatest

node.js - 如何创建一个自定义管道来接收对象作为 Angular 4 中的过滤器

html - 如何使用 Angular 路由设置主页路由 url?

ngrx - 了解 Ngrx OnRunEffects

angular - 在 Ionic 2 中隐藏状态栏

javascript - 为什么要将 Redux Action 创建者返回的 Action 括在括号中?