Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular2异步http请求_Javascript_Twitter Bootstrap_Angular_Ngx Bootstrap - Fatal编程技术网

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);
    }
}