在NGRX Store中,通常使用选择器(selectors)来从存储中获取数据。但有时可能需要在不使用订阅的情况下获取存储中的数据。以下是一种解决方法:
import { Store, createSelector } from '@ngrx/store';
const mySelector = createSelector(
(state: AppState) => state.myData, // 获取存储中的数据
(myData) => myData.property // 返回需要的数据
);
constructor(private store: Store) {}
getData() {
const data = mySelector(this.store.getState()); // 使用选择器函数获取数据
console.log(data); // 打印数据
}
请注意,此方法适用于简单的场景,当数据发生更改时,需要手动调用选择器函数来获取最新的数据。如果数据频繁变化,建议使用订阅方式来获取数据。