I was using the Tour Heroes tutorial: https://angular.io/tutorial/toh-pt6#search-by-name to create my own search bar. However the diff '[object Object]' error appeared and although lots of answers say that I need to convert the object in array form, in the tutorial, it says the async pipe take cares of that for me so i don't have to subscribe.
Thank you in advance!
Error message
offer-search.component.html
<input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
<ul class="search-result">
<li *ngFor="let offer of offers$ | async" >
{{offer.name}}
</li>
offer-search.component.ts
...
import { Offer } from '../model/offer';
import { OfferService } from '../offer.service';
@Component({
selector: 'app-offer-search',
templateUrl: './offer-search.component.html',
styleUrls: ['./offer-search.component.css']
})
export class OfferSearchComponent implements OnInit {
@Input('offerP') offerProperty: string;
offers$: Observable<Offer[]>;
private searchTerms = new Subject<string>();
constructor(private offerService: OfferService) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.offers$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.offerService.searchOffersByProperty(term, this.offerProperty)),
);
}
}
offer.service.ts
...
searchOffersByProperty(term: string, prpty: string): Observable<Offer[]> {
if (!term.trim()) {
// if not search term, return empty hero array.
return of([]);
}
let searchURL = this.url + `/offers/?foodOfferer=${this.authService.credential.foodOfferer.id}&${prpty}=${term}`;
return this.http.get<any>(searchURL, {
headers: this.headers,
responseType: 'json',
}).pipe(catchError(this.handleError('searchOffersByProperty', '')));
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…