2017-11-15 5 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, 
    }))); 
} 

그런 다음 아래처럼이 메도을 사용할 수 있습니다 : 당신은 비동기 HTTP 호출을하는

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

가져 오기. 도와 줘서 고마워! :) – Jim

1

. 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 
    }); 
} 
관련 문제