0

问题:

我有组件和网址,例如:

https://127.0.0.0/car/carName1/view1

ngOnInit(): void {
    this.store$.dispatch(Actions.loadView());    
  }

此调度操作和效果从服务中获取单个视图并将其添加到集合中

状态将如下所示:

{
  views: {

     view1: {
        data: []
     }

     view2: {
        data: []
     }
  }
}

现在,在同一个组件中,我需要从包含更多我需要的数据的视图中获取更多信息,或者换句话说,我需要从中选择一些

    ngOnInit(): void {
        this.data$ = this.store$.select(Selectors.selectMoreData);
        this.store$.dispatch(Actions.loadView());    
      }

问题是Selectors.selectMoreData需要视图名称/键。因为 state 有更多的视图,而不仅仅是当前组件的一个视图。

我有什么可能?就像在效果中使用路由器存储并从 url 获取密钥一样?或者我应该退后一步,因为这是完全错误的。

4

1 回答 1

2

更新

在评论中讨论后,我的答案将是下一个:尽一切ngOnInit努力避免在这里和那里传递变量的复杂性。

ngOnInit(): void {
  this.data$ = this.store$.select(Selectors.selectMoreData, this.viewName);
  this.store$.dispatch(Actions.loadView());    
}

或者在router-store

ngOnInit(): void {
  this.data$ = this.store$.pipe(
    select(selectRouteParam('viewName')),
    switchMap(viewName => combineLatest([
      of(viewName),
      this.store$.select(Selectors.selectMoreData, this.viewName)),
    ]),
    map(([viewName, data]) => ({viewName, data}));
  );

  this.store$.dispatch(Actions.loadView());    
}

并在模板中

<ng-container *ngIf="data$ | async as data">
  <child [view]="data.viewName" [data]="data.data"></child>
</ng-container>

或者在this.activatedRoute

ngOnInit(): void {
  this.data$ = this.activatedRoute.paramMap.pipe(
    map(params => params.get('viewName')),
    switchMap(viewName => combineLatest([
      of(viewName),
      this.store$.select(Selectors.selectMoreData, this.viewName)),
    ]),
    map(([viewName, data]) => ({viewName, data}));
  );

  this.store$.dispatch(Actions.loadView());    
}

原来的

您错过了第三个选项 - 要使用将为您的组件提供数据的解析器ActivatedRoute.data,您可以在此处的答案中找到一个示例:https ://stackoverflow.com/a/61836566/13112018 。


再说回viewName。您可以将其添加为路线的数据,然后也可以访问它router-store

例如,您可以定义这样的路线。

{
    path: 'test',
    component: TestComponent,
    data: {
        viewName: 'test',
    },
},

然后用来router-store选择它

this.store.select(selectRouteData).subscribe(console.log); // {viewName: 'test'}
于 2020-05-18T18:55:44.760 回答