2017-08-05 85 views
1

以下是我的代码!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有效!

+0

尝试getProdukte(){返回this.http.get('http://cube-developing.de/connect.php ').map(res => res.json()。records);} – amishra

+0

也不起作用:/ – Degcube

+0

您的回复仍然无效,或者我应该说** **是有效的,因为它最初与斜线,但瓦特如果你解析它,它会变成无效的JSON。 – Alex

回答

0

如果API正确返回数据,则需要解析组件constructoronInit中的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 

    } 
+0

undefined main.bundle.js(1036,44) – Degcube

+0

您收到哪个组件的错误 –

+0

sry im有点新的角度,即时获取2未定义在这两个组件 – Degcube