[英]Angular2 asynchronous http request
我在這里有一個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
輸入可以更新下拉菜單中的信息。 但是,由於對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)
}
);
}
據我在您的代碼中看到的那樣,您的服務返回的是可觀察到的:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.