I'm struggling to receive a JSON response that contains an array with every declaration, including the user and category information. I currently have a static solution, but I want to implement a dynamic approach and I'm facing difficulties making it work.
EDIT: I have hardcoded the 'id' in the method, which limits me to fetching only one declaration. My goal is to create a loop that retrieves all the declarations from http://localhost:8080/declaraties. I attempted nested HTTP requests but without success.
Code:
data.service.ts
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
@Injectable()
export class DataService {
constructor(private http: Http) { }
url = 'http://localhost:8080/declaraties/';
getAllesVanDeclaraties(id: number): Observable<any> {
return Observable.forkJoin([
this.http.get('http://localhost:8080/declaraties/' + id).map(res => res.json()),
this.http.get('http://localhost:8080/declaraties/' + id + '/gebruiker').map(res => res.json()),
this.http.get('http://localhost:8080/declaraties/' + id + '/categorie').map(res => res.json())
])
.map((data: any[]) => {
const declaraties: any = data[0];
const gebruiker: any[] = data[1];
const categorie: any[] = data[2];
declaraties.gebruiker = gebruiker;
declaraties.categorie = categorie;
return declaraties;
});
}
}
row.component.html
<ng-container *ngFor="let decl of data; let i = index;">
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<th>{{i + 1}}</th>
<td>{{decl['gebruiker'].naam}}</td>
<td>{{decl.datumIngediend}}</td>
<td>{{decl.omschrijving}}</td>
<td>{{decl['categorie'].naam}}</td>
<td>€ {{decl.bedrag}}</td>
</tr>......
row.component.ts
import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import {DataService} from './data.service';
@Component({
selector: 'app-row',
templateUrl: './row.component.html',
styleUrls: ['./app.component.css']
})
export class RowComponent implements OnInit {
data: any = [];
constructor(private dataService: DataService) {
}
ngOnInit() {
this.dataService.getAllesVanDeclaraties(2).subscribe( data => {
console.log(data);
this.data.push(data);
});
}
}
I attempted to use nested HTTP requests, but I'm not receiving any responses.