如何使用ngFor获取和显示Ngrx角度存储数据

时间:2019-06-11 13:03:16

标签: redux angular7 ngrx ngrx-store ngrx-reducers

我正在状态中将表单数据存储在数组中。我正在接收数组,但是数组以嵌套形式存在。我不知道如何显示它。

//查看Viewcomponent.ts

customerarray: Customer[];
ngOnInit() {
// this.customerObs = this.store.select('customerList');
this.store.select<Customer[]>('customerList').subscribe(res =>                     
    {
      this.customerarray = res;
      console.log(res);
      console.log(this.customerarray);
    });
}

// viewcomponent.html

<li *ngFor="let customer of customerarray; i as index">
      <span>{{ i + 1}}.</span>  {{customer.customer.name}}
</li>

// reducer.ts

import { Customer } from '../app/models/customer';
import { ADD_CUSTOMER } from '../app/store/action';
import * as CustomerAction from '../app/store/action';
const initialState = {
    customer: [
        new Customer('Steve', 'Yellow'),
        new Customer('RDJ', 'Red')
    ]
};

export function CustomerReducer(state = initialState, action: CustomerAction.AddCustomer) {
    console.log(state.customer);
    switch (action.type) {
        case CustomerAction.ADD_CUSTOMER:
            return {`enter code here`

            ...state,                
            customer: [...state.customer, action.payload]
            };

        default:
            return state;
    }
}

2 个答案:

答案 0 :(得分:0)

我假设您的Customer类是这样定义的-

export class Customer {
  name: string;
  color: string;
  constructor(n: string, c: string) {
     this.name = n;
     this.color = c;
  }
}

我还假设您的选择器this.store.select<Customer[]>('customerList')从您的customer返回initialState属性。

如果我是正确的,那么您应该像这样更新模板-

<li *ngFor="let customer of customerarray; i as index">
      <span>{{ i + 1}}.</span>  {{customer.name}}
</li>

答案 1 :(得分:0)

我认为这是一个变更检测问题。 您的组件不会在此订阅上呈现。

尝试-

.ts文件-

customersObs:Observable<Customer[]>
constructor() {
 this.customersObs = this.store.select<Customer[]>('customerList');
}

.html文件-

<li *ngFor="let customer of cusomersObs | async; i as index">
      <span>{{ i + 1}}.</span>  {{customer.name}}
</li>