0
votes

How do I get the state to render when the app loads? When I run this app the state is empty until I click the button with the click function. I tried doing this.store.select but I never get the requested state. Todo_List is an object inside ngrx store I want to render its list property which is an array

App.Component.ts

import { Component,OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState } from './AppState.model';
import { Add_Todo, Load_Todos } from './ngrx.actions';
import { Todo } from './ngrx.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private store: Store<AppState>,private http:HttpClient ){
  }
  todo_list$: Observable<Array<Todo>>
  loading$: Observable<Boolean>;
  ngOnInit(): void{
    console.log(this.store)
    this.store.dispatch(new Load_Todos());
    console.log(this.store)
    this.todo_list$ = this.store.source._value.Todo_List.list
    this.loading$ = this.store.source._value.Todo_List.loading
  }
  title = 'angular-todo-list';

  click(){

  //   console.log(this.store)
  //   this.store.dispatch(new Add_Todo({
  //     message: 'heyyyyy',
  //     time: '3pm',
  //     date:'05/16/20',
  //     user_id: 1,
  // }));

  this.todo_list$ = this.store.source._value.Todo_List.list
}
}

App.Component.ts

<button (click)="click()"id="enter"><i class="fas fa-pencil-alt"></i></button>
        <div class="row">
            <div class="listItems col-12">
                <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
            <li *ngFor="let x of todo_list$">{{x.message}}</li>
                </ul>
            </div>
        </div>
    </div>
1

1 Answers

0
votes

2 things I’m noticing:

  1. If you want data out of the store, you have to use a selector. Check out the ngrx.io website for exact instructions and examples. But it looks something like this: todos$ = this.store.pipe(select(getTodos));

  2. NgRx is Reactive Extensions for Angular, so the selectors return Observables. To display these on the component template, you need to use the async pipe like so:

    {{ todos$ | async }}

This takes care of subscribing and unsubscribing from the observable.

Start with those, and hopefully things will start to take shape.