网站搜索

php - Angular 将数组当作对象处理且不显示值


// 根据讨论进行了更新

我尝试通过HTTP请求获取JSON对象(任务),并将它们解析到我自己的类中,以在我的HTML页面(任务概览)上显示它们。

这是我得到的:

这是我的 PHP 返回的 JSON 数组:

    {"result":[{"id":"3","znumber":"vor21423"},{"id":"2","znumber":"vor213"}]}

这是我在 angular.io 教程中的最后一次尝试。我测试了许多答案,但它们大多数都涉及 .json(),而这已不再是 HTML 客户端的一部分。

export class ApiComponent {
 private apiUrl = 'http://localhost:81/work/get.php';

 results: Steve[];

 constructor(private http: HttpClient) {
 }

 ngOnInit() {
   this.getSteves();
 }

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
      .subscribe(data => {
        this.results = data.result
          .map(steve => new Steve(steve.id, steve.zNumber));
            console.log(this.results);
            console.log(data);
      });
  }
}

界面

import { Steve } from './Steve';
export interface ItemsResponse {
  results: Steve[];
}

HTML

<div>
  <div *ngFor="let steve of results">
    <p> - {{steve.id}}</p>
    <p> - {{steve.zNumber}}</p>
  </div>
</div>

史蒂夫班

export class Steve {
  public id = 0;
  public zNumber = '';

  constructor(id: number, zNumber: string) {
    this.id = id;
    this.zNumber = zNumber;
  }
}

应用程序接口

<?php 
require_once('db.php');

$sql = 'SELECT * FROM jobs ORDER BY id DESC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode(array('result' => $data));
} else {
    echo 0;
}
?>

答案#1

首先,你接收的不是数组,而是一个对象,所以你需要从对象 result 中获取数组。其次,如果你想让数组中的对象成为 Steve 的实例,你需要明确告诉 Angular。

你 ItemsResponse 实际上是这样的(注意是 result 而不是 results):

import { Steve } from './Steve';

export interface ItemsResponse {
  result: Steve[];
}

该请求应显示您正在获取类型为 ItemsResponse 的响应。

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
     .subscribe(data => {
       // your array is in 'result' object of your response
       this.results = data.result
         // create instances of your class
         .map(steve => new Steve(steve.id, steve.znumber))
     });
  }

答案#2

你至少在使用 Angular 4 版本。在 4 版本中,Angular 团队决定隐式解析 JSON 结果,因此你不必在每个 Ajax 请求中编写 JSON.parse(json.result)。

在你的示例中,你将服务器返回的值:result 替换为 steves,然后你尝试访问它:data['steves'],但在截图中你可以看到值已经被 Angular 的隐式 JSON 解析提取出来,你处理的是一个对象数组。

所以 data['steves']、data['result'] 等等将始终是未定义的,因为 Angular HttpClient 服务(在版本 4 中取代了 Http 服务)在返回数据之前已经解析了 JSON。

只需将:this.results=data['steves']; 替换为 this.results=data;,一切就会正常工作。