Can someone assist me with this issue? I have a code snippet that retrieves characters from an API and allows me to search for specific characters using input.
I am trying to display different messages on my HTML page based on the search results. If no items are found, I want to show "No items found"; if data is loading, I want to display "Loading".
The problem I'm encountering is that the "No items found" message always appears, even when the application has just started and the "Loading" message is not displayed at all. Could someone please help me identify where the issue lies? Thank you in advance.
HTML
<div *ngFor="let character of (characters | async)">
{{ character.name }}
</div>
<div *ngIf="loading">
Loading...
</div>
<div *ngIf="!response.length && !loading">
No items found
</div>
Typescript
public characters: Observable<DifferentCharacter[]>;
public loading: boolean = false;
public response: DifferentCharacter[] = [];
public gettingAndInputCharacters(): void {
const inputSearchItem = localStorage.getItem('inputCharacterValue') || '';
const filterCharacters = (value: string) => {
return this.charactersService.getAllCharacters(value).pipe(
map((response) => {
const characters = response.results.sort((a, b) => {
return a.name.localeCompare(b.name);
});
return value ? characters.filter((character: DifferentCharacter) => {
const name = character.name.trim().toLowerCase();
const searchInputItem = value.trim().toLowerCase();
return name.startsWith(searchInputItem) ||
searchInputItem.split('').every((char: string, index: number) => char === name.charAt(index));
}) : characters;
}),
catchError(() => of([]))
);
};
this.form.controls['searchCharacterInput'].setValue(inputSearchItem);
this.form.controls['searchCharacterInput'].valueChanges.subscribe(value => {
this.loading = true;
localStorage.setItem('inputCharacterValue', value);
this.characters = filterCharacters(value).pipe(finalize(() => this.loading = false));
this.characters.subscribe(value => {
this.response = value
})
});
this.characters = filterCharacters(inputSearchItem);
}