简体   繁体   English

如何从商店取得状态? 角/ NGRX

[英]How take state from store? angular/ngrx

i long time work with react/redux and now i trying to learn angular/ngrx. 我长期与react / redux合作,现在我尝试学习angular / ngrx。

And I had questions 我有问题

how write in store? 如何在商店写? In redux store i just connect used function connect, and in angular i connect like this 在redux存储区中,我只是连接使用过的函数connect,而在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');
            }

next i use todos$ for cycle in template, but if i console.log(todos$) its just object of store, and i can't find my store state, how can I read state from the store? 接下来,我在模板中使用todos$进行循环,但是如果我console.log(todos$)它只是商店的对象,而我找不到我的商店状态,如何从商店中读取状态?

You can use rxjs operator do to show sideeffects dont forget to import it. 您可以使用rxjs运算符do来显示副作用,不要忘记导入它。

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

another way will be to subscribe but this will defeat the purpose of ngrx. 另一种方法是订阅,但这将破坏ngrx的目的。 And you will not use async pipe in template and also you will need to unsubscribe. 而且您将不会在模板中使用异步管道,并且还需要取消订阅。

storeSub: Subscription;

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

todo$ is an observable of your state. todo $是您状态的可观察值。

You can use it in controller like this: 您可以像这样在控制器中使用它:

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

Or in your template like this: 或在您的模板中这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM