gpt4 book ai didi

json - 嵌套的 HTTP 调用 Angular 4

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:09 24 4
gpt4 key购买 nike

我试图在 json 中获得响应,我在其中获得一个数组,其中包含每个声明,其中包含用户和类别。我已将其静态修复,但我想使其动态化,但似乎无法使其正常工作。

编辑:我在方法中静态插入“id”,所以我只得到一个声明。我想创建某种循环,我可以在其中取回 http://localhost:8080/declaraties 上的所有声明.我已经尝试过嵌套 http 但没有成功。

代码:

数据.服务.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;
});
}
}

行.组件.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>&euro; {{decl.bedrag}}</td>

</tr>......

行.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);
});
}
}

我尝试发出嵌套的 http 请求,但没有收到任何响应。

最佳答案

像这样尝试:

Observable.forkJoin([
this.http.get('http://localhost:8080/declaraties/' + id),
this.http.get('http://localhost:8080/declaraties/' + id + '/gebruiker'),
this.http.get('http://localhost:8080/declaraties/' + id + '/categorie')
])
.subscribe((data: any) => {
console.log('data[0]', data[0].json())
console.log('data[1]', data[1].json())
console.log('data[2]', data[2].json())
})

关于json - 嵌套的 HTTP 调用 Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47595186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com