Clearing subscription when navigating to other page not working
As the first comment suggests, this does seem overly complicated. I hope this example may provide a simpler setup in creating a search list with applied filters.
First, let's simplify your search result service. I typically follow the strategy that a service should be as generic as possible. So, all we want to do is request and return the complete list of results.
export class SearchresultsService {
public searchresult$: Observable<ResultData[]>;
constructor(private httpClient: HttpClient) {
const url = `${environment.ssoUrl}api/SearchrResult`;
this.searchresult$ = this.httpClient.get<ResultData[]>(url, { params, responseType: 'json' });
}
}
Service files are where you can define observables, but you should try to avoid subscriptions. Leave that to the components that depend on the service's data.
Next, I created a sample list component that manages filters as local state. I took some liberties in assuming how your filter object actually works.
export class ListComponent {
public searchResults$: Observable<ResultData[]>;
private filter = new BehaviorSubject<Filter>(new Filter());
constructor(private searchService: SearchresultsService) {
this.searchResults$ = this.searchService.searchResult$.pipe(
switchMap(results => this.filter.pipe(
map(filter => results.filter(result => result[a] === filter[a]))
))
);
}
public setFilter(criteria: any) {
const newFilter = new Filter(criteria);
this.filter.next(newFilter);
}
}
Let's go through this step by step:
- We declare a BehaviorSubject that initializes with the default empty filter object.
- We add the method
setFilter()
that lets you create and emit a new filter from the same BehaviorSubject. - In our constructor, we define an observable that takes all the data from our service HTTP request.
- We use
switchMap()
to subscribe to our filter BehaviorSubject to get the latest filtered value and apply it.
From here, you can subscribe to the searchResult$
observable in your component's template using the async
pipe. This will automatically handle the subscribe and unsubscribe events throughout the component's lifecycle.
<ul class="search-results">
<li *ngFor="let result of searchResult$ | async">
<!-- do things with {{result}} -->
</li>
<ul>
Now, when you click through the CRUD page, the list component will be destroyed along with all subscriptions. When you navigate back, the filter
BehaviorSubject will be re-initialized with the default blank filter.