如何在Angular项目的组件中显示从PHP返回的json数据

时间:2018-01-15 12:27:39

标签: php json angular interface ngfor

我正在尝试将从PHP返回的数据显示为JSON数组到我的组件中。

在此ngOnInit()中,我添加了以下脚本:

ngOnInit(){
this.http.get('http://aff.local/getPartners.php').subscribe(
    (response: Response) =>{
      const data = response.json() as Partners;
      console.log(data);
      //this.keys.push(this.data);
    },
    error =>{
      console.log('error');
    }
  )
}

PHP脚本如下:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
require_once("./serverConnection.php");

class affiliatePartner
{
    public function getPartners(){
        global $conn;
        $result = array();
        $getPartners = "SELECT partner_name FROM partner";
        $execGetPartners = $conn->prepare($getPartners);
        $execGetPartners->execute();
        $result = $execGetPartners->fetchAll();

        // foreach($result as $res)
        // {
        //  $res=array('partner_name'=>$result['partner_name']);
        // }
        return json_encode($result);
    }
}
?>

我得到了以下结果:

enter image description here

然后,我想在div中显示UdemyNike

  <ul *ngFor="let datas of data;">
    {{datas}}
  </ul>

但组件中没有任何内容。

我搜索了一下,有些人使用了界面,所以我创建了一个界面:

import { Injectable } from '@angular/core'

export interface Partners{
    name: String;
}

在主要组成部分:

import { Partners } from './Interfaces';

我将脚本改为:

ngOnInit(){
this.http.get('http://aff.local/getPartners.php').subscribe(
    (response: Response) =>{
      const data = response.json() as Partners;
      console.log(data.name);
      //this.keys.push(this.data);
    },
    error =>{
      console.log('error');
    }
  )
}

但我的div中仍然没有显示结果。

2 个答案:

答案 0 :(得分:2)

在组件的顶部,您需要声明一个变量。然后,您需要将返回的结果存储在该变量中。

public partners: any = [];

ngOnInit(){
  this.http.get('http://aff.local/getPartners.php').subscribe(
    (response: Response) =>{
      this.partners = response.json() as Partners;
      console.log(this.partners);
    },
    error =>{
      console.log('error');
    }
  )
}

完成后,您可以在html中使用以下内容

<ul *ngFor="let partner of partners">
    <li>{{partner.partner_name}}>/li>
</ul>

要在下拉菜单中显示

<select>
    <option *ngFor="let partner of partners; let i = index">{{partner.partner_name}}</option>
</select>

如果你正在使用Angular5

<select>
    <option *ngFor="let partner of partners; index as i">{{partner.partner_name}}</option>
</select>

答案 1 :(得分:1)

您应该在班级的开始时创建一个变量

data: Array<Partners>;

然后在订阅中,不要为从api获取的值创建常量,而是执行此操作

this.data = response.json() as Partners;

视图应显示现在的响应

<ul><li *ngFor="let datas of data">{{datas.partner_name}}</li><ul>