2016-10-17 14 views
0

私はのコンポーネントをSemantic-UIとAngular2約束して使用しています。非同期ソース(Angular2約束)で検索

foo.component.ts

export class FooComponent implement OnInit { 
    myData:any = []; 
    ... 

    ngOnInit() { 
     this.myDataService.getData().then(myData => this.myData = myData); 
     $('.ui.search').search({ source: this.myData }); 
    } 
} 

foo.component.html

<div class="ui search"> 
    <input class="prompt" type="text"> 
    <div class="results"></div> 
</div> 

しかしsourceは常に空です は、ここに私のコードです。私はこれがデータサービスへの非同期呼び出しのために起こると思います。

どうすればこの問題を解決できますか?

答えて

0

現在、ngOnInitが実行されてもデータが到着していないため、初期値(空の配列)で検索を初期化しています。

export class FooComponent implement OnInit { 
    ... 

    ngOnInit() { 
     this.myDataService.getData().then(myData => { 
      $('.ui.search').search({ source: myData }); 
     }); 
    } 
} 

はセマンティックUIの検索コンポーネントは、検索を維持するための組み込みのメカニズムを持っていることに留意してください:

この特定のケースのための最も簡単な解決策は、あなたのデータが検索コンポーネントを初期化する前に到着するのを待つだけですリモートの結果 - usage section of the docsで確認して、代わりに利用できるかどうか確認してください。

+0

私はドキュメントでそのリンクを読んだことがありますが、検索コンポーネントに "Angular2 way"(約束)を適用する方法がわかりません。手伝って頂けますか? – smartmouse

1

fstanisの回答は技術的に正しいです。しかし、私は彼が逃したものに少し追加しました。 OPはコンポーネントレベルのプロパティで結果を保持していましたが、返された結果を直接使用するのではなく、後で使用することができます。私はこれを達成するもう一つの可能​​な方法をこの答えに加えています。

1)の方法のOPはそれをやろうとしました。これは、あなたのサービスが

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import {Observable} from 'rxjs/Rx'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class MyDataService { 

    constructor(private http:Http) { } 

    getData(){ 
    return this.http.get('some/api/url').map(
     res => res.json() 
    ); 
    } 

} 

希望のようになります方法です

export class FooComponent implement OnInit { 
    myData:any = []; 
    ... 

    ngOnInit() { 
     this.myDataService.getData().subscribe(
      data => { 
       this.myData = data; 
       $('.ui.search').search({ source: this.myData }); 
      }, 
      error => { 
       // Write your logic here if an error was occurred. Use the variable "error" which has info about what happened. 
      }, 
      () => { 
       // This fires when the call has been finished. Just like .complete in jQuery.get or jQuery.post. So that you can do necessary operations after everything is completed. 
      } 
     ); 
    } 
} 

購読2角度を使用して

export class FooComponent implement OnInit { 
    myData:any = []; 
    ... 

    ngOnInit() { 
     this.myDataService.getData().then(myData => { 
      this.myData = myData; 
      $('.ui.search').search({ source: this.myData }); 
     }); 
    } 
} 

2)これは役に立ちます。

+0

ご協力いただきありがとうございますが、両方のソリューションが動作しません。検索ポップアップが空です。 – smartmouse

+0

角度2のサービスがサーバーからデータを正しく取得しているかどうか確認しましたか?私の答えを更新して、サービスの見え方のサンプルを含めてみましょう。 –

+0

セマンティックUI検索コンポーネントの 'mockResponse'を使って動作します。 – smartmouse