This is some code from an angular component. It is a search component where characterIndexes is an array of search results.
The search results are retrieved by typing in a searchbox which triggers the searchtrigger or searchEmptyTrigger depending on its content. After getting the first results I have to perform another http.post() to get the names belonging to the indexes so I can sort them ( I omitted that part from the code ). Then the results are inserted in the characterIndex-array.
A similar thing happens when searchEmptyTrigger is triggered. Except for the characterIndex-array is just set to empty and no http-requests are needed.
The issue I run into is that in some cases, when the searchEmptyTrigger is triggered, the code from the searchtrigger is still running ( due to delays because of the http-requests ).
The result is that the characterIndexes are empty first. And then it would fill up again after receiving the result from the http-request in the searchtrigger.
So the big question is: 'How to cancel my running http.post() while it is waiting for a response?'
public characters: any[];
public characterIndexes: number[];
let searchBox = document.getElementById('search-box');
let searchTrigger = fromEvent(searchBox, 'input')
.pipe(
map((event: any) => event.target.value ),
filter( text => text.length > 2 ),
debounceTime( 500 ),
distinctUntilChanged(),
switchMap( text => ajax(`https://esi.evetech.net/v2/search/?categories=character&datasource=tranquility&language=en-us&search=^${text}&strict=false`)
)
);
let searchEmptyTrigger = fromEvent(searchBox, 'input')
.pipe(
map((event: any) => event.target.value ),
filter( text => text.length <= 2 )
);
searchTrigger.subscribe( response => {
if( response.response.character ){
let characterIndexes = response.response.character;
this.http.post('https://esi.evetech.net/latest/universe/names/?datasource=tranquility', characterIndexes)
.subscribe( (charactersInfo: any[]) => {
// do some stuff with this.characterIndexes and this.characters = [];
});
} else {
this.characterIndexes = [];
this.characters = [];
}
});
searchEmptyTrigger.subscribe( () => {
// reset values
this.characterIndexes = [];
this.characters = [];
});
PS: I am also open for an alternate approach that performs the same operations as the code above, where I can cancel the http-request.