【发布时间】:2017-10-27 09:38:34
【问题描述】:
我有后端服务器,可为我提供有关家具的信息。我在 Angular (Typescript) 中有一个前端服务,用户将在其中输入相关单词,该服务会建议类似的单词。
问题
当用户删除单词并且搜索栏为空时,建议仍会显示。搜索栏为空时如何删除建议?
可注入服务
@Injectable()
export class SearchService {
apiRoot: string = 'myEndPoint';
constructor(private http: Http) {
}
search(term: string): Observable<SearchItem[]> {
// HTTP GET with parameter JSON as mentioned below(inpjson)
let inpjson = {'keyword': term, 'language': 'en'}
let apiURL = `${this.apiRoot}?inputAsJson=${JSON.stringify(inpjson)}`;
return this.http.get(apiURL)
.map(res => {
return res.json().conceptOverview.map(item => {
return new SearchItem(
item.url,
item.translatedURL
);
});
});
}
}
HTTP 响应
{
'searchTyp': 'ExplorativeSearch',
'conceptOverview' : [
{
'url': 'someurl1',
'translatedURL': 'somestuff1'
},
{
'url': 'someurl2',
'translatedURL': 'somestuff2'
}
....
]
}
应用组件
class AppComponent {
private loading: boolean = false;
private results: Observable<SearchItem[]>;
private searchField: FormControl;
constructor(private http: SearchService) {
}
ngOnInit() {
this.searchField = new FormControl();
this.results = this.searchField.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.do(_ => this.loading = true)
.switchMap(term => this.http.search(term))
.do(_ => this.loading = false)
}
doSearch(term: string) {
this.http.search(term)
}
}
参考
【问题讨论】:
标签: angular typescript observable