Angular2 асинхронный HTTP-запрос
У меня есть 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 для предоставления функциональности typeahead моему приложению. В настоящее время, когда я набираю ввод, он вызывает searchIngredients
какие обновления ingredients
так что ввод typeahead может обновлять информацию в выпадающем меню. Тем не менее, так как призыв к 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)
}
);
}
1 ответ
Насколько я вижу в вашем коде, ваш сервис возвращает наблюдаемый:
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);
}
}