Angular 7 NGRX Store 的状态未定义。
创始人
2024-10-16 19:33:17
0

在Angular 7中,如果NGRX Store的状态未定义,可能有几种原因。以下是一些可能的解决方法和代码示例:

  1. 确保在应用程序的根模块(通常是AppModule)中导入了StoreModule.forRoot方法,并在imports数组中添加它。
import { StoreModule } from '@ngrx/store';
import { reducer } from './reducers';

@NgModule({
  imports: [
    StoreModule.forRoot({ app: reducer }) // 使用你的reducer替换'reducer'
  ],
  ...
})
export class AppModule { }
  1. 确保你的reducer函数正确地处理了未定义的状态。可以使用ES6的默认参数来设置初始状态。
export function reducer(state = initialState, action: Action) {
  switch (action.type) {
    ...
    default:
      return state;
  }
}
  1. 确保在组件中正确地选择状态。使用select方法从store中选择状态,并使用async管道在模板中订阅状态的更新。
import { select } from '@ngrx/store';
import { Observable } from 'rxjs';

@Component({
  ...
})
export class MyComponent {
  myState$: Observable;

  constructor(private store: Store) {
    this.myState$ = this.store.pipe(select('myState'));
  }
}
  1. 确保在组件中订阅了状态的更新。可以在ngOnInit生命周期钩子中订阅状态,并在组件销毁时取消订阅。
import { Subscription } from 'rxjs';

export class MyComponent implements OnInit, OnDestroy {
  myState: any;
  subscription: Subscription;

  constructor(private store: Store) { }

  ngOnInit() {
    this.subscription = this.store.pipe(select('myState')).subscribe(state => {
      this.myState = state;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

以上是一些常见的解决方法和代码示例,可以根据具体情况进行调整。

相关内容

热门资讯

大神推荐!we-poker辅助... 自定义wepoker一直输的号能继续打吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑...
必知教程!sohoo竞技联盟辅... 1、必知教程!sohoo竞技联盟辅助器,wejoker辅助软件价格,安装教程(有挂方法);详细教程。...
如何分辨真伪!wepoker私... 如何分辨真伪!wepoker私人局可以透视,wepoker底牌透视脚本,AI教程(有挂教程)1、点击...
玩家必备教程!wepoker有... 玩家必备教程!wepoker有辅助功能吗,wepoker数据分析工具,wpk教程(有挂技巧);wep...
揭秘攻略!wepoker亲友圈... 揭秘攻略!wepoker亲友圈有用吗,wepoker透视app下载,可靠教程(有挂透明);1.wep...
一分钟揭秘!wepoker插件... 一分钟揭秘!wepoker插件功能辅助器,fishpoker透视,技巧教程(有挂技巧)是由北京得we...
分享实测!wepoker软件靠... 分享实测!wepoker软件靠谱么,pokemmo免费脚本,力荐教程(有挂神器);建议优先通过wep...
一分钟教你!wepoker手机... 一分钟教你!wepoker手机版透视脚本,wepoker辅助器激活码,新版2025教程(有挂方法)是...
分享一款!wepoker有没有... 分享一款!wepoker有没有机器人,wepoker透视是真的吗,透明教程(有挂透明)是一款可以让一...
终于知道!wepoker私人局... 终于知道!wepoker私人局辅助器怎么用,哈糖大菠萝能开挂吗,揭秘教程(有挂技巧)1、玩家可以在w...