FILTER SERVICE - implementation for basic data filtering using observables
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Filter } from '../../models/filter.model';
import { Convert } from '../../utils/converter';
@Injectable({
providedIn: 'root'
})
export class FilterService {
private currentFilter$ = new BehaviorSubject<{ page: number, limit: number }>({
page: 0,
limit: 20
});
constructor() { }
private init(name: string) {
let filterStr = localStorage.getItem(name);
if (filterStr) {
this.currentFilter$.next(Convert.fromJson<Filter>(filterStr))
} else {
localStorage.setItem(name, Convert.ToJson<Filter>(this.currentFilter$.value));
}
}
private saveFilter(name: string, filter: Filter) {
this.currentFilter$.next(filter);
localStorage.setItem(name, Convert.ToJson<Filter>(filter));
}
public getFilter(name: string): Observable<Filter> {
this.init(name);
return this.currentFilter$;
}
public nextPage(name: string) {
let filter = this.currentFilter$.value;
filter.page = filter.page + 1;
this.saveFilter(name, filter);
}
// Other methods omitted for brevity...
}
DOCUMENT ROUTE - dynamic parameter type
: 302 = invoice, 306 = delivery note etc.
{ path: 'documents/:type', component: DocumentsComponent },
DOCUMENT COMPONENT
@Component({
selector: 'app-documents',
templateUrl: './documents.component.html',
styleUrls: ['./documents.component.scss']
})
export class DocumentsComponent extends Unsubscriber implements OnInit {
displayedColumns: string[] = ['number', 'customerName', 'date', 'paymentDate', 'settledStatus', 'net', 'vat', 'gross'];
documentsDataSource: Document[] = [];
sortColumn = '';
sortDirection: SortDirection = '';
searchText = '';
title = '';
filters?: FilterItem[] = [];
type = 0;
// Constructor and other code left unchanged...
});
UNSUBSCRIBER
import { Injectable, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Injectable()
export abstract class Unsubscriber implements OnDestroy {
subscription = new Subscription();
constructor() { }
ngOnDestroy(): void {
console.log("Unsubscribing...");
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
RESULT - The issue arises with multiple subscriptions when changing routes in the document context. This can be resolved by properly unsubscribing to the previous subscriptions. When navigating between different components like Products or Customers before going back to Documents, everything functions correctly.
How can I address this problem?