2017-11-15 20 views
1

これは私の現在のコードです。この場合、どのようにしてrowData値を返すことができますか?角度4の戻り値は定義されていません

private createRowData() { 
const rowData: any[] = []; 

this.http 
    .get(`/assets/json/payment.json`) 
    .toPromise() 
    .then(response => response.json()) 
    .then(data => { 
    data.items.map(elem => { 
     rowData.push({ 
     id: elem.id, 
     total_amount: elem.total_amount, 
     status: elem.status, 
     sent: elem.sent, 
     }); 
    }); 
    }); 
return rowData;} 

私は戻ってくる前にrowDataを操作しようとしていましたが、私には未定義でした。

+3

可能性のある重複した[非同期呼び出しからの応答を返すには?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-コール)(TL; DR:できません。最後の '.then'コールによって作成された約束を返す必要があります) –

答えて

2

あなたのメソッドは、変換されたデータの約束を返す必要があります。最後のコールバックでは、変換されたレスポンスを返す必要があります。あなたはそれを行うために矢印関数の暗黙の復帰に頼ることができます。 array.proptype.mapは各値が変換される新しい配列を返すので、変数rowDataは必要ありません。あなたがしなければならないすべては次のとおりです。

private createRowData() { 
    return this.http // Return the promise 
    .get(`/assets/json/payment.json`) 
    .toPromise() 
    .then(response => response.json()) 
    .then(data => data.items.map(elem => ({ // Return the transformed data by the then callback 
     id: elem.id, 
     total_amount: elem.total_amount, 
     status: elem.status, 
     sent: elem.sent, 
    }))); 
} 

その後、あなたは以下のように、このMethodeのを使用することができます:

this.createRowData().then(rowData => console.log(rowData)) 
+0

入手してください。ご協力ありがとうございました! :) – Jim

1

あなたは、非同期のHTTP呼び出しを行っています。 return rowData;行が実行されると呼び出しが完了せず、したがって未定義になります。これを解決するには、関数から約束を返して、.then()コールを使用して関数を呼び出す場所からrowDataを取得します。

private createRowData() { 
    const rowData: any[] = []; 

    return this.http // <- Return promise 
    .get(`/assets/json/payment.json`) 
    .toPromise() 
    .then(response => response.json()) 
    .then(data => { 
    data.items.map(elem => { 
     rowData.push({ 
     id: elem.id, 
     total_amount: elem.total_amount, 
     status: elem.status, 
     sent: elem.sent 
     }); 
     return rowData; 
    }); 
    }); 
//return rowData; // <- This is undefined because the call isn't complete yet 
} 

ngOnInit() { 
    this.createRowData().then(data => { 
    console.log(data) // <- rowData 
    }); 
} 
関連する問題