Javascript Angular2异步http请求
我在这里有一个Javascript Angular2异步http请求,javascript,twitter-bootstrap,angular,ngx-bootstrap,Javascript,Twitter Bootstrap,Angular,Ngx Bootstrap,我在这里有一个http请求功能components.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)]="a
http
请求功能components.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">
我怎么跑
this.searchIngredients()
return Observable.of(
this.ingredients
);
所以我只返回一次可观察的这个。成分更新了吗
我的searchComponents
功能如下
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);
}
}
那么按照您的说法,我的函数只会在从get请求中实际填充成分后返回成分?它必须能够在每次击键时更新配料。目前,它将显示上一次击键的搜索结果,而不是当前击键的搜索结果,这不太有用。你说的“每次击键”是什么意思?每个来自标签的输入?是的,每次输入值更改创建plnkr时都会调用主要的typeahead函数,我认为你的问题不是很清楚
export class YourComponent {
public ingredients;
ngOnInit() {
this.ingredients = this.searchIngredients("");
}
searchIngredients(){
this.ingredients = this.searchIngredients(this.query);
}
}