2017-07-09 241 views
0

我這裏有ingredients.serviceAngular2異步HTTP請求

searchIngredients(query:string) { 
    let search = this.ingredientsUrl + "?q=" + query 
    return this.http.get(search, {headers:this.headers}) 
     .map(res=>res.json()); 
} 

我的HTML代碼如下的http請求功能...

<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的自舉到我的應用程序提供預輸入功能。目前,當我輸入輸入內容時,它會調用searchIngredients,它會更新ingredients,這樣輸入的內容可以更新下拉菜單中的信息。但是,由於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) 
     } 
    ); 
} 
+0

創建一個plnkr,你的問題在我看來不是很清楚 – Skeptor

回答

0

至於我可以在你的代碼中看到,您的服務將返回觀察到:

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

所以你說的方式,我的功能只會返回成分,一旦配料實際上從獲取請求填充?它必須能夠在每次擊鍵時更新成分。目前,它將顯示最後一次擊鍵的搜索結果,而不是當前的搜索結果,這不是太有用 –

+0

「每次擊鍵」是什麼意思?每個輸入來自標籤? –

+0

是的,每次輸入值發生變化時,都會調用主鍵入函數 –