import { Injectable } from '@angular/core' ; import { BehaviorSubject , Subject } from 'rxjs' ; import { FilterAddEvent } from './events/filter-add-event' ; import { FilterEvent } from './events/filter-event' ; import { FilterRemoveAllEvent } from './events/filter-remove-all-event' ; import { FilterRemoveEvent } from './events/filter-remove-event' ; import { Filter } from './interfaces/filter.interface' ; @ Injectable ( ) export class FilterService { /** The list of active filters */ filters$ = new BehaviorSubject < Filter [ ] > ( [ ] ) ; /** Emit all the events when they occur */ events$ = new Subject < FilterEvent > ( ) ; add ( filter ) { if ( this . isSelected ( filter ) || filter . initial ) { return ; } this . filters$ . next ( [ ... this . filters$ . value , filter ] ) ; this . events$ . next ( new FilterAddEvent ( filter ) ) ; } remove ( filter ) { if ( ! this . isSelected ( filter ) ) { return ; } this . filters$ . next ( this . filters$ . value . filter ( _filter => _filter !== filter ) ) ; this . events$ . next ( new FilterRemoveEvent ( filter ) ) ; } removeAll ( ) { this . filters$ . next ( [ ] ) ; this . events$ . next ( new FilterRemoveAllEvent ( ) ) ; } isSelected ( filter ) { return this . filters$ . value . indexOf ( filter ) > - 1 ; } }