2017-10-22 6 views
2

例のように配列内の検索の代わりにアンギュラマテリアル2オートコンプリートを使用してAPIを検索しようとしています。これは私が試したものです:マテリアル2(角度4)オートコンプリートから外部APIの検索

HTML:

<mat-form-field fxFlex="33" class="mr-20 mt-20"> 
    <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl"> 
    <mat-autocomplete #auto="matAutocomplete"> 
    <mat-option *ngFor="let state of filteredStates | async" [value]="state.name"> 
     <span>{{ state.name }}</span> 
    </mat-option> 
    </mat-autocomplete> 
</mat-form-field> 

TS:しかし

this.stateCtrl = new FormControl(); 
this.filteredStates = this.stateCtrl.valueChanges 
    .startWith(null) 
    .debounceTime(400) 
    .do(value => { 
    this.ClientsService.search(value).then(res => { 
     console.log(res, 'oi'); 
     this.states = res; 
    }) 
    }); 

、私が入力したとき、私はこのエラーを取得:Error: Cannot find a differ supporting object 'e' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

eことは何だとI検索フィールドに入力します。私がサーバーから受け取っている応答は、オブジェクトが入っている配列です。

私はここで何が欠けていますか?

+1

あなたは内の値を得るのですか'filteredStates' –

+1

サーバーから取得したデータをJSONに解析するのを忘れてしまいました。 JSON.parse()を実行すると正常に動作するはずです – TruckDriver

+0

@Timothy私はサービス終了時のデータを解析しています。私は再びデータを解析しようとしたとき、私は同じエラーが発生しました。 – WagnerMatosUK

答えて

2

テンプレートに表示する数値がstatesの場合は、受信データを保存する場所に応じて、テンプレートに表示する内容を指定します。

そう:TSと

<mat-option *ngFor="let state of states" [value]="state.name"> 

代わりの

<mat-option *ngFor="let state of filteredStates | async" [value]="state.name"> 

:ランダムチャック・ノリスはジョークと

this.filteredStates = this.stateCtrl.valueChanges 
    .startWith(null) 
    .debounceTime(400) 
    .do(value => { 
    this.ClientsService.search(value).then(res => { 
     console.log(res, 'oi'); 
     this.states = res; 
    }) 
    }) 
    .subscribe() 

Plunkerを;)https://stackblitz.com/edit/angular-uu4cya?file=app%2Fapp.component.ts

+0

私はあなたのコードを試してみましたが、次のエラーが出ています: 'タイプ 'サブスクリプション'はタイプ 'Observable 'に割り当てられません。 プロパティ '_isScalar'がタイプ 'Subscription'にありません。 ''プロパティ 'unsubscribe'がタイプ 'Observable 'に存在しません。どのバージョンのAngularを使用していますか?私は4.4.5とMaterial 2、beta 12になっています – WagnerMatosUK

+1

ええ、 'filteredStates'はObservableの代わりに' Subscription'でなければならないので、 'filteredStates:Subscription; 'と宣言する必要があります:) – Alex

+0

ありがとう!それはトリックをした:) – WagnerMatosUK

1

ほとんどの場合、サーバーから取得した結果を解析するのを忘れている可能性があります。

this.states = JSON.parse(res); 

これで問題は解決します。

+0

前のコメントで述べたように、データはサービス側で解析されているため、そうではありません。私もあなたの提案を試みたが、私はまだ同じエラーがあります。 – WagnerMatosUK

関連する問題