【问题标题】:Is there a type safe way to access store members in ngrx/store?是否有一种类型安全的方式来访问 ngrx/store 中的商店成员?
【发布时间】:2017-05-16 20:31:34
【问题描述】:

我一直在使用 angular2 浏览 ngrx/store 的文档

https://github.com/ngrx/store

https://github.com/ngrx/example-app

上面的示例应用程序暗示我应该使用以下方式访问商店的可观察成员:

counter: Observable<number>;
constructor(private store: Store<AppState>){
    this.counter = store.select('counter');
}

使用字符串 'counter' 访问对象成员感觉与 TypeScript 是对立的。是否有一种类型安全的方式来访问商店成员?

【问题讨论】:

    标签: angular typescript ngrx ngrx-store


    【解决方案1】:

    如果你看select的实现:

    export function select<T, R>(pathOrMapFn: any, ...paths: string[]): Observable<R> {
      let mapped$: Observable<R>;
      if (typeof pathOrMapFn === 'string') {
        mapped$ = pluck.call(this, pathOrMapFn, ...paths);
      }
      else if (typeof pathOrMapFn === 'function') {
        mapped$ = map.call(this, pathOrMapFn);
      }
      else {
        throw new TypeError(`Unexpected type ${ typeof pathOrMapFn } in select operator,`
          + ` expected 'string' or 'function'`);
      }
      return distinctUntilChanged.call(mapped$);
    }
    

    您会看到传递字符串等效于pluck,但传递选择器函数等效于map - 这是类型安全的。

    所以传递一个选择器函数。这就是example app 所做的。

    使用您的示例:

    counter: Observable<number>;
    constructor(private store: Store<AppState>){
      this.counter = store.select(state => state.counter);
    }
    

    【讨论】:

    • 赞美杰布斯/蜘蛛猪!我非常担心在我的项目中引入一堆魔术字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2020-08-31
    相关资源
    最近更新 更多