I have search input where user will enter value and matched records will be shown. I am calling getSearchResults
in ngOnit
.
I need to show result when found else if api status is false then need to show 'No results found.'
But when I get api response true then it first shows 'No results found' and then data found.
How can I avoid showing 'No results found' first if api status is true?
I have tried different *ngIf
conditions but nothing working as expected.
Ts
searchResults:any;
searchResultsFlag:boolean = false;
horseResults:any;
userResults:any;
getSearchResults(){
this.SpinnerService.show();
this.horseService.SearchProfile(this.searchValue).subscribe((results) => {
if (results['status'] === false) {
this.SpinnerService.hide();
this.searchResultsFlag = false;
} else {
this.SpinnerService.hide();
this.searchResultsFlag = true;
this.searchResults = results['data'];
this.horseResults = this.searchResults.horses;
this.userResults =this.searchResults.users;
}
});
}
HTML
<div *ngIf="searchResultsFlag">
<h5 *ngIf="userResults && userResults.length>0">Matched User Results</h5>
<div >
<div *ngFor="let user of userResults">
....
</div>
</div>
<h5 *ngIf="horseResults && horseResults.length>0">Matched Horse Results</h5>
<div >
<div *ngFor="let horse of horseResults">
....
</div>
</div>
</div>
<p *ngIf="!searchResultsFlag">No results found.</p>
CodePudding user response:
It happens because while the http request to the API occurs, your searchResultsFlag os setted as false.
To fix it, you should create a loading flag:
searchResults:any;
searchResultsFlag:boolean = false;
loadingFlag = false;
horseResults:any;
userResults:any;
getSearchResults(){
this.SpinnerService.show();
this.loadingFlag = true;
this.horseService.SearchProfile(this.searchValue).subscribe((results) => {
if (results['status'] === false) {
this.SpinnerService.hide();
this.searchResultsFlag = false;
} else {
this.SpinnerService.hide();
this.searchResultsFlag = true;
this.searchResults = results['data'];
this.horseResults = this.searchResults.horses;
this.userResults =this.searchResults.users;
}
this.loadingFlag = false:
});
}
HTML
<div *ngIf="searchResultsFlag">
<h5 *ngIf="userResults && userResults.length>0">Matched User Results</h5>
<div >
<div *ngFor="let user of userResults">
....
</div>
</div>
<h5 *ngIf="horseResults && horseResults.length>0">Matched Horse Results</h5>
<div >
<div *ngFor="let horse of horseResults">
....
</div>
</div>
</div>
<p *ngIf="!searchResultsFlag && !loadingFlag">No results found.</p>
CodePudding user response:
You should initialize loadingFlag=true, by default you are loading data, so you wont show text of No Result Data until you get response and modify loadingFlag=false