Angular 4使用json填充表格
问题描述:
以下是我的代码!Angular 4使用json填充表格
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class ProdukteService {
constructor(private http: Http) {}
getProdukte() {
return this.http.get('assets/demo/data/produkte.json')
.toPromise()
.then(res => <any[]> res.json().records)
.then(records => { return records; });
}
}
与该代码+ HTML我可以填充我的表和它的工作!:
<p-dataTable [value]="produkte" [style]="{'margin-bottom':'20px'}">
<p-header>Recent Sales</p-header>
<p-column field="Produktitel" header="Vin"></p-column>
<p-column field="Preis" header="Year"></p-column>
</p-dataTable>
但现在我想/需要的JSON从数据库这样的:
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
@Injectable()
export class ProdukteService {
constructor(private http: Http) {}
getProdukte() {
return this.http.get('http://cube-developing.de/connect.php')
.toPromise()
.then(res => <any[]> res.json().records)
.then(records => { return records; });
}
}
但那不起作用...我需要改变什么才能使这个工作? JSON有效!
答
如果API正确返回数据,则需要解析组件constructor
或onInit
中的Promise。
ngOnInit() {
this.ProdukteService
.getProdukte()
.then(result => {console.log(result); this.data = result)}) // assign data to variable
.catch(error => console.log(error));
}
您可以使用观测量 acheive相同。
服务
getProdukte() {
return this.http.get('http://cube-developing.de/connect.php')
.map(res => res.json().records)
}
在组件
ngOnInit() {
this.ProdukteService
.getProdukte()
.subscribe(result => {console.log(result); this.data = result)}); // assign data to variable
}
尝试getProdukte(){返回this.http.get('http://cube-developing.de/connect.php ').map(res => res.json()。records);} –
amishra
也不起作用:/ – Degcube
您的回复仍然无效,或者我应该说** **是有效的,因为它最初与斜线,但瓦特如果你解析它,它会变成无效的JSON。 – Alex