[英]Why doesnt my app state render to the app in angular Ngrx
How do I get the state to render when the app loads?如何让 state 在应用程序加载时呈现? When I run this app the state is empty until I click the button with the click function.
当我运行这个应用程序时,state 是空的,直到我单击按钮并单击 function。 I tried doing this.store.select but I never get the requested state.
我试过这样做 this.store.select 但我从来没有得到请求的 state。 Todo_List is an object inside ngrx store I want to render its list property which is an array
Todo_List 是 Ngrx 商店内的 object 我想渲染它的列表属性,它是一个数组
App.Component.ts应用组件.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应用组件.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>
2 things I'm noticing:我注意到的两件事:
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.
查看 ngrx.io 网站以获取确切的说明和示例。 But it looks something like this:
todos$ = this.store.pipe(select(getTodos));
但它看起来像这样:
todos$ = this.store.pipe(select(getTodos));
NgRx is Reactive Extensions for Angular, so the selectors return Observables. NgRx 是 Angular 的响应式扩展,因此选择器返回 Observables。 To display these on the component template, you need to use the
async
pipe like so:要在组件模板上显示这些,您需要像这样使用
async
pipe:
{{ todos$ | {{待办事项$ | async }}
异步 }}
This takes care of subscribing and unsubscribing from the observable.这负责订阅和取消订阅 observable。
Start with those, and hopefully things will start to take shape.从这些开始,希望事情会开始成形。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.