简体   繁体   中英

How take state from store? angular/ngrx

i long time work with react/redux and now i trying to learn 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

        @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?

You can use rxjs operator do to show sideeffects dont forget to import it.

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. 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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