import { ImmutableContext } from '@ngxs-labs/immer-adapter' ; import { Action , NgxsAfterBootstrap , Selector , State , StateContext } from '@ngxs/store' ; import { removeItem } from '@ngxs/store/operators' ; import { tap } from 'rxjs/operators' ; import { AppNotification } from './app-notification.model' ; import { AddNotification , DeleteNotification , FetchNotifications , MarkAllAsRead , MarkAsRead , } from './notifications.actions' ; import { NotificationsService } from './notifications.service' ; import { Injectable } from '@angular/core' ; dynamic @ State < AppNotification [ ] > ( { name : 'notifications' , defaults : [ ] , } ) @ Injectable ( { providedIn : 'root' , } ) export class NotificationsState implements NgxsAfterBootstrap { constructor ( private notificationsService ) { } @ Selector ( ) static unReadCount ( state ) { return state . filter ( ( note ) => ! note . read ) . length ; } ngxsAfterBootstrap ( ctx ) { console . log ( 'State initialized, now getting Notifications.' ) ; } @ ImmutableContext ( ) @ Action ( AddNotification ) add ( ctx , { payload } ) { ctx . setState ( ( state ) => { state . push ( payload ) ; return state ; } ) ; } @ Action ( FetchNotifications , { cancelUncompleted : true } ) fetchNotifications ( { getState , patchState , setState } ) { return this . notificationsService . getAll ( ) . pipe ( tap ( ( res ) => setState ( res ) ) ) ; } @ Action ( DeleteNotification ) delete ( ctx , { payload } ) { ctx . setState ( removeItem < AppNotification > ( ( note ) => note . id === payload . id ) ) ; } @ ImmutableContext ( ) @ Action ( MarkAsRead ) markAsRead ( ctx , { payload } ) { ctx . setState ( ( state ) => { state [ state . findIndex ( ( note ) => note . id === payload . id ) ] . read = true ; return state ; } ) ; } @ ImmutableContext ( ) @ Action ( MarkAllAsRead ) markAllAsRead ( ctx ) { ctx . setState ( ( state ) => { state . forEach ( ( item ) => { item . read = true ; } ) ; return state ; } ) ; } }