2017-07-18 5 views
1

私の目標は、実行中のローカルElasticSearchサーバーのNG2-webapp内のサンプルデータを取得して表示することです。Angular2 + Elasticsearch:Elasticsearchサーバーから取得したJSONデータを計算するときに「未定義のプロパティを取得する」エラー

これまでのところ、NPM Elasticsearch Typescript packageを使用してコンポーネントtest-es-typesを作成しました。

これは.tsコードである:

import { Component, OnInit } from '@angular/core'; 
    import * as elasticsearch from 'elasticsearch'; 

    @Component({ 
    selector: 'app-test-es-types', 
    templateUrl: './test-es-types.component.html', 
    styleUrls: ['./test-es-types.component.scss'] 
    }) 

    export class TestEsTypesComponent implements OnInit { 

    constructor() { } 

    ngOnInit() { 

    // Setting up Elasticsearch Client 
    var client = new elasticsearch.Client({ 
    host: 'http://localhost:9200', 
    log: 'trace' 
    }); 

    console.log("Client:", client); 

    // Elasticsearch Server Ping 
    client.ping({ 
    // ping usually has a 3000ms timeout 
    requestTimeout: 1000 
}, function (error) { 
    if (error) { 
    console.trace('elasticsearch cluster is down!'); 
    } else { 
    console.log('All is well'); 
    } 
}); 

// first we do a search, and specify a scroll timeout 
var allTitles: string[] = []; 
console.log("Erzeuge allTitles Array..."); 
client.search({ 
    index: 'bank', 
    // Set to 30 seconds because we are calling right back 
    scroll: '30s', 
    searchType: 'query_then_fetch', 
    docvalueFields: [''], 
    q: 'Avenue' 
}, function getMoreUntilDone(error, response) { 
    // collect the first name from each response 
    console.log("allTitles gefüllt: ", allTitles); 
    response.hits.hits.forEach(function (hit) { 
    allTitles.push(hit.fields.firstname); 
    }); 

    if (response.hits.total !== allTitles.length) { 
    // now we can call scroll over and over 
    client.scroll({ 
     scrollId: response._scroll_id, 
     scroll: '30s' 
    }, getMoreUntilDone); 
    } else { 
    console.log('every "test" title', allTitles); 
    } 
}); 

} 

} 

ES-サーバがローカルホスト上で実行されている:9200及び予想通り(コンソールに応じて)照会データを返します。配列(allTitles)にこのデータを置くしようとしたときしかし、私は、次のコンソールエラーが表示されます。

Uncaught TypeError: Cannot read property 'firstname' of undefined 

にconsole.logは明らかに動作しないようにallTitlesは、(長さ0)空であることを私に伝えます。私はまだオブジェクトを配列に変換する複雑さを理解していないようですね?

+0

私は、あなたのコンポーネントが多くの異なる懸念事項に関与しているので、懸念の分離についていくつか読むことをお勧めします –

答えて

0

考えられる1つの問題は、応答に正しくアクセスしていないことです。試してみてください

client.search({...... 
............. 
............. 
}).then(function(resp){ 
     console.log("allTitles gefüllt: ", allTitles); 
     response.hits.hits.forEach(function(hit){ 
      allTitles.push(hit.fields.firstname); 
     }); 
}, function(err){ 
     console.log(err); 
}); 

詳細はquickstart guideです。

関連する問題