我在这里有一个http
请求函数ingredients.service
searchIngredients(query:string) {
let search = this.ingredientsUrl + "?q=" + query
return this.http.get(search, {headers:this.headers})
.map(res=>res.json());
}
我的HTML代码如下......
<input [(ngModel)]="asyncSelected"
[typeahead]="dataSource"
(typeaheadLoading)="changeTypeaheadLoading($event)"
(typeaheadNoResults)="changeTypeaheadNoResults($event)"
(typeaheadOnSelect)="typeaheadOnSelect($event)"
typeaheadOptionsLimit="10"
typeaheadOptionField="name"
typeaheadAsync="false"
placeholder="Search for Ingredient"
class="form-control">
这使用ngx-bootstrap为我的应用程序提供预先输入功能。目前,当我输入输入时,它会调用searchIngredients
更新ingredients
,以便输入输入可以更新下拉菜单中的信息。但是,由于对searchIngredients
的调用是异步的,因此它不会及时更新ingredients
,以便在下拉菜单中显示。
public getIngredientsAsObservable(query: string): Observable<any> {
console.log("observable")
this.query = query
this.searchIngredients()
return Observable.of(
this.ingredients
);
}
我该怎么办
this.searchIngredients()
return Observable.of(
this.ingredients
);
这样我只会在this.ingredients
更新后才返回observable吗?
我的searchIngredients
功能如下
searchIngredients(){
this.ingredientService.searchIngredients(this.query)
.subscribe(
data=>{
this.ingredients = data.results
console.log("Success")
},
error=>{
console.log(error)
},
()=>{
console.log("Request Complete")
console.log(this.ingredients)
}
);
}
答案 0 :(得分:0)
就我在代码中看到的而言,您的服务会返回observable:
public searchIngredients(query:string) {
let search = this.ingredientsUrl + "?q=" + query
return this.http.get(search, {headers:this.headers})
.map(res=>res.json());
}
在您的组件中,您只需将其连接到现场:
export class YourComponent {
public ingredients;
ngOnInit() {
this.ingredients = this.searchIngredients("");
}
searchIngredients(){
this.ingredients = this.searchIngredients(this.query);
}
}