I have a REST API returning a Hashmap <String,<String,Integer>>. I need to use this Hashmap Json to display a table in Angular 5. I have tried the following till now, but the table is still empty. I am not very sure how to access the nested object in the model class properly in the HTML File. Where am I going wrong?
This is the frequency-table.model.ts file where I have defined the structure of the HashMap.
export interface FrequencyTable {
obj: {
key: String;
val: {
key_in: String;
val_in: Number;
};
}
}
This is the HTML File
<div class="container">
<div class="row">
<table class="table">
<thead class="thead-inverse">
<tr>
<th class="text-center">Thread Name</th>
<th class="text-center">Query</th>
<th class="text-center">Frequency</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let post of _postsArray">
<td class="text-center" style="width: 15px;">{{post.key}}</td>
<td class="text-center" style="width: 15px;">{{post.val.key_in}}</td>
<td class="text-center" style="width: 200px;">{{post.val.val_in}}</td>
</tr>
</tbody>
</table>
</div>
This is the frequency-table.component.ts file
export class FrequencyTableComponent implements OnInit {
_postsArray: FrequencyTable[];
constructor(private tableService: TableService) { }
getPosts(): any {
this.tableService.getPosts()
.subscribe(
resultArray => this._postsArray = resultArray,
error => console.log("Error :: " + error)
)
}
ngOnInit() {
}
This is the service.ts file
@Injectable()
export class TableService {
constructor(private http: HttpClient) {}
getPosts(): Observable<FrequencyTable[]> {
return this.http
.get('\getQueryCount')
.map((response: Response) => {
return <FrequencyTable[]>response.json();
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}
This is the REST API returning Hashmap json:
@RestController
public class QueryCounterController{
@Autowired
ReadFileService rfservice;
@GetMapping("/getQueryCount")
@ResponseBody
public Map<String, Object> getQueryCount() throws IOException{
String filename = "file.txt";
return (rfservice.readFile(filename));}
}
Sample Json:
{
"key1": {
"xyz": 3,
"abc": 2
},
"key-2": {
"pqr": 3,
"uvw": 2
}
}
var obj = this.getPosts();- this line of code returns immediately without waiting for the http request to complete. You should move your logic insidesubscribefunction.