Here is my service code snippet:
@Injectable({
providedIn: 'root',
})
export class UserDataService {
constructor(private http: HttpClient) {}
tableData = <SampleDataStructure[]>[]; // SampleDataStructure is the interface
url: string =
'https://some_sample_data.json'; //dummy url
getTableData(): SampleDataStructure[] {
this.http.get(this.url).subscribe((data) => {
for (let user in data) {
let userData = <SampleDataStructure>{};
//setting required fields as per SampleDataStructure interface
userData.S_No = data[user]['s.no'];
userData.country = data[user]['country'];
userData.location = data[user]['location'];
userData.num_backers = data[user]['num.backers'];
userData.end_time = data[user]['end.time'];
this.tableData.push(userData);
//console.log(this.tableData); // *shows data here in tableData as expected
}
});
//console.log(this.tableData); //**shows empty array here
return this.tableData;
}
}
I'm expecting tableData to be populated with required data. Its instead showing me empty array (at line marked with comment **). Though its showing expected data at line marked with comment *
I know I'm doing some very silly mistake, can someone please help me on this. Thanks in advance!
CodePudding user response:
A subscription is working asynchronously. That means that the url is called and the program don't wait until it finish (http.get(this.url)). So the return this.tableData; is executed after the http.get is executed, but anytime before or after the get finish to fetch the data.
That's why the console.log(this.tableData); alwways shows data, and the return this.tableData; can return nothing or data.
The best is that getTableData return the observable like this signature:
public getTableData(): Observable<SampleDataStructure[]> {
return this.http.get(this.url).pipe(map(data) => {
