如何从 angular 组件中的 ngrx 存储获取内容

How to get stuff from ngrx store in an angular component

我在组件中有这段代码:

    ngDoCheck(){
    this.store.select('info').pipe(map((val: Info) => {
        window.alert(val.user.name);
        this.user.name = val.user.name;
    }));
}

首先我想验证这不是订阅可观察对象而是像我想的那样异步检查值。

其次我想知道为什么它不起作用,使用调试器我看到 val 未定义但是商店存储了 属性 所以 属性 存储在商店中但是这个代码未到达。

我也看到地图里面的代码永远不会到达。 谢谢。任何帮助表示赞赏。祝你有个美好的一天。

你需要订阅才能监听状态变化,你不需要强制输入,因为如果你输入正确 "InfoState" ts 继承会给你正确的类型订阅

this.store.select('info').subscribe(info => {
    window.alert(info.user.name);
    this.user.name = info.user.name;
});

标准方式是订阅商店,完成后取消订阅。

storeSubscription: Subscription;

ngOnInit() {
  this.storeSubscription = this.store.select('info').subscribe(info => {
    window.alert(info.user.name);
    this.user.name = info.user.name;
  });
}

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

通过使用 Subscription,我们确保商店订阅了它的特定切片 ('info'),因此该切片中的任何更改都会通知您的组件。我们还必须在不使用时取消订阅以释放钩子,以避免不必要的内存使用。