如何从商店获取状态? angular/ngrx

How take state from store? angular/ngrx

我和 react/redux 一起工作了很长时间,现在我正在努力学习 angular/ngrx。

我有问题

店里怎么写?在 redux store 中,我只连接使用过的函数 连接,在 angular 我这样连接

        @Component({   selector: 'home',
            templateUrl: './home.html' }) export class HomeComponent implements OnInit {

            console = console;
            todos$: Observable<any>;
            todo: string;
            todoDate: string;
            indexToEdit: number | null;


            constructor(private store: Store<any>) {}

            ngOnInit() {
                this.todos$ = this.store.select('todoReducer');
            }

接下来我在模板中使用 todos$ 作为循环,但是如果我 console.log(todos$) 它只是商店的对象,我找不到我的商店状态,我如何从商店读取状态?

你可以使用 rxjs 运算符 do 来显示副作用不要忘记导入它。

this.todos$ = this.store.select('todoReducer').do(res => console.log(res))

另一种方式是订阅,但这会破坏 ngrx 的目的。而且你不会在模板中使用异步管道,你也需要取消订阅。

storeSub: Subscription;

this.storeSub = this.store.select('todoReducer').subscribe((data) => {
  console.log(data);
  this.todos = data;
})

todo$ 是您的状态的可观察值。

你可以像这样在控制器中使用它:

this.todo$.subscribe(state => console.log(state));

或者在你的模板中这样:

{{ todo$ | async }}
<input type="text" name="myfield" (change)="modifyField($event.target.value)" [value]="(todo$ | async)?.myfield"></input>