簡體   English   中英

對Angular和NgRx中的嵌套狀態更改做出反應

[英]React to nested state change in Angular and NgRx

請考慮以下示例

// Example state
let exampleState = {
  counter: 0;
  modules: {
    authentication: Object,
    geotools: Object
  };
};

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

MyAppComponent我們對狀態的counter屬性發生的更改做出反應。 但是如果我們想對狀態的嵌套屬性做出反應 ,例如modules.geotools呢? 似乎應該有可能調用store.select('modules.geotools') ,因為將所有內容放在全局狀態的第一級似乎不利於整體狀態結構。

更新

@cartant的答案肯定是正確的,但Angular 5中使用的NgRx版本需要一些不同的狀態查詢方式。 我們的想法是,我們不能只提供store.select()調用的密鑰,我們需要提供一個返回特定狀態分支的函數 讓我們將其稱為stateGetter並將其寫入以接受任意數量的參數(即查詢深度)。

// The stateGetter implementation
const getUnderlyingProperty = (currentStateLevel, properties: Array<any>) => {
  if (properties.length === 0) {
    throw 'Unable to get the underlying property';
  } else if (properties.length === 1) {
    const key = properties.shift();
    return currentStateLevel[key];
  } else {
    const key = properties.shift();
    return getUnderlyingProperty(currentStateLevel[key], properties);
  }
} 

export const stateGetter = (...args) => {
  return (state: AppState) => {
    let argsCopy = args.slice();
    return getUnderlyingProperty(state['state'], argsCopy);
  };
};

// Using the stateGetter
...
store.select(storeGetter('root', 'bigbranch', 'mediumbranch', 'smallbranch', 'leaf')).subscribe(data => {});
...

select將嵌套鍵作為單獨的字符串,因此您的select調用應該是:

store.select('modules', 'geotools')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM