2017-08-05 88 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