我在我的应用中使用@ ngrx / store而我在app状态数组中推送新对象并在componentsnet.html中显示
file.ts //下面是我的reducer和app状态接口,用于保存通知数组
import { Action } from '@ngrx/store';
//app state interface immutable array of notification
export interface AppState {
notifications: Array<Notification>;
}
export interface Notification {
name: string;
id:string
}
export const ACTIONS = {
ADD_NOTIFICATION: 'ADD',
}
//custom action interface for send payload with action while dispatching action.
export interface CustomAction extends Action {
type: string;
payload?:Notification;
}
// my reducer to add Notification object to app state array.
export function notificationReducer(state: Array<Notification> = [], action: CustomAction): Array<IFreelancer> {
switch (action.type) {
case ACTIONS.ADD_NOTIFICATION:
return [...state, action.payload];
default:
return state;
}
}
//NotificationShowComponent.ts to get data from app store and display
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState, Notification, ACTIONS } from '../file.ts';
import * as Rx from 'RxJS';
@Component({
selector: ' app-NotificationShowComponen',
templateUrl: './NotificationShowComponent.html',
styleUrls: ['./NotificationShowComponent.css']
})
export class NotificationShowComponent implements OnInit {
notifications: Rx.Observable<Array<Notification>>; //observable array of notification
constructor(private store: Store<AppState>) {
this.notifications = store.select('notifications');
}
ngOnInit() {
}
}
// * ngfor在新添加到应用状态数组NotificationShowComponent.html
时显示通知我在shownotification.html中遇到问题,即使reducer正在向数组添加新对象,for循环没有执行,而notification.length也没有显示递增值。
<li class="treeview" *ngFor="let notification of (notifications|async)">
<span>Hire <h1>{{notification.name}}</h1></span>
</li>
{{(notifications|async).length}} //not incrementing