我這裏有ingredients.service
Angular2異步HTTP請求
searchIngredients(query:string) {
let search = this.ingredientsUrl + "?q=" + query
return this.http.get(search, {headers:this.headers})
.map(res=>res.json());
}
我的HTML代碼如下的http
請求功能...
<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的自舉到我的應用程序提供預輸入功能。目前,當我輸入輸入內容時,它會調用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
更新?
我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)
}
);
}
創建一個plnkr,你的問題在我看來不是很清楚 – Skeptor