【问题标题】:Angular2 NgRx.Store and Extracting Selectors for ReuseAngular2 NgRx.Store 和提取选择器以供重用
【发布时间】:2016-09-05 21:41:09
【问题描述】:

这是我的商店:

{
  comments:{
    entities:{id:comment}
    ids:[ids...]
  },
  videos:{
    entities:{id:video}
    ids:[ids...]
  }
}

以下是我的预测:

export function getVideoById(id) {
  return (state$: Observable<AppState>) => _getVideoById(s, id);
}

function _getVideoById(s: AppState, id: string) {
  return s.videos.entities[id];
}

export function getCommentsByVideoId(id) {
  return (state$: Observable<AppState>) =>
    state$.map((s: AppState) => _getCommentsByVideoId(s, id))
}

function _getCommentsByVideoId(s: AppState, id) {
  let currentVid = _getVideoById(s, id);
  return currentVid.commentIds.map(id => s.comments.entities[id]);
}

以下是我通过投影访问数据的方式:

this.video$ = this.store.let(getVideoById(this.videoId));
this.comments$ = this.store.let(getCommentsByVideoId(this.videoId));

我的问题:

我目前将我的投影分成两部分,以便我可以在其他投影中重复使用某些部分(ie: let currentVid = _getVideoById(s, id);)

有没有一种方法可以将我的投影声明为一个块并在其他投影中重用它们?

一种投影组合?

我见过这样的例子,但每次他们“缩小”||“缩小”投影范围(即:我们从视频开始,我们在视频中更深入,我们永远无法回到其他分支,例如“cmets”)。我对这一切都很陌生,所以非常感谢一些建议,

谢谢。

【问题讨论】:

  • 您是否查看过ngrx/example-app 中的composed selectors 以获得指导?
  • 是的,我确实看过它一段时间(谢谢),我发现它很复杂,所以我想出了上面的解决方案......

标签: angular selector projection ngrx


【解决方案1】:

我想出了一种装饰器服务(仍然不确定它是否“正确的方式”) 示例:

@Injectable()
export class MyFeatureState {
    // Inject Store to Construtor

   get allFeatureProperties() {
        return this.store.select(s => s.feature.properties).map(toArray)
   }

   getFeaturePropertyById(id:string) {
       return this.store.select(s => s.feature.properties[id])           
   }

   get activeFeatureProperty() {
       return Observable.combineLatest(
           this.allFeatureProperties,
           this.store.select(s => s.feature.activeProperty)
       ).map(([ap, active] => ap[active])
   }
}

interface FeatureState {
    properties:{[id:string]:FeatureProperty};
    activeProperty:string;
}

希望你能得到我的方法 :) 你也可以使用一些 memoize 功能来缓存 observables(它们仍然会发出新值)

Br

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多