asp.net web api - Angular2 filter observable with switchMap -
i'm doing term search using angular2 , webapi using method described in numerous angular2 tutorials.
in service:
search(term: string): observable<userlist[]> { return this.http.get(this.usersearchurl + term) .map((response: response) => response.json()) .catch(this.handleerror); }
in component:
ngoninit(): void { this.users = this.searchtermstream .debouncetime(300) .distinctuntilchanged() .switchmap((term: string) => term ? this.userservice.search(term) : observable.of<userlist[]>([])) .catch(error => { console.log(error); return observable.of<userlist[]>([]); }); }
what on service side keep track of last search. if initial search "b" , search "bo" should not have make call webapi since have results need need filter down further. assume doing observables out of question/difficult since subscribe stream don't know observables yet. thought maybe doing promise might easier, i'm not sure how handle component side of subject() , switchmap() seem observables
this like use on service side:
searchpromise(term: string): promise<userlist[]> { if (this.lastusedterm.length > 0 && term.indexof(this.lastusedterm) == 0) { this.lastusedsearch = this.lastusedsearch.then(x => x.filter(z => z.firstname.startswith(term))); } else { this.lastusedsearch = this.http.get(this.usersearchurl + term) .topromise() .then((response: response) => response.json()) .catch(this.handleerror); } this.lastusedterm = term; return this.lastusedsearch.then(x => x.filter(z => z.firstname.startswith("bob"))); }
Comments
Post a Comment