0

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 功能。目前,当我输入输入时,它会调用searchIngredientswhich updatesingredients以便预先输入的输入可以更新下拉菜单中的信息。但是,由于调用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)
        }
      );
}
4

1 回答 1

0

据我在您的代码中看到的,您的服务返回 observable:

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);
    }
}
于 2017-07-09T20:23:57.197 回答