简体   繁体   English

如何从 Angular 4 中的 MySQL 表填充下拉框

[英]How to populate a drop-down box from a MySQL table in Angular 4

In PHP and HTML I just simply used to fetch data in array and show it in the select box as shown below:在 PHP 和 HTML 中,我只是简单地用于获取数组中的数据并将其显示在选择框中,如下所示:

<?php

mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT nameid FROM PC";
$result = mysql_query($sql);

echo "<select name='PcID'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['nameid'] . "'>" . $row['nameid'] . "</option>";
}
echo "</select>";

?>

I mean I can connects to a MySQL database, issue query, and outputs <option> tags for a <select> box from each row in the table我的意思是我可以连接到 MySQL 数据库,发出查询,并为表中每一行的<select>框输出<option>标签

But how do I achieve same in Angular 4?但是我如何在 Angular 4 中实现相同的目标?

The best way is to fetch data in a JSON and then show it on the frontend by creating an API?最好的方法是获取 JSON 中的数据,然后通过创建 API 将其显示在前端? Or there is some other way?或者有其他方法吗?

The best way would be to return the data as JSON.最好的方法是将数据作为 JSON 返回。 Using rxjs subscribe you can fetch the data like this使用 rxjs subscribe 您可以像这样获取数据

 users:any[]= [];
fetchData(){
  this.http.get("users/all-users")
      .subscribe((res)=>{
        this.users = res.data
       })

  }

So in the html it would be something like所以在html中它会是这样的

<select>
    <option *ngFor="let user of users" value="user.id">
  {{ user.name }}
</option>

 </select>

So in your php return data like this所以在你的 php 中返回这样的数据

function getUsers(){

  mysql_connect('hostname', 'username', 'password');
   mysql_select_db('database-name');

   $sql = "SELECT nameid FROM PC";
   $result = mysql_query($sql);

  return ["data"=>$result];
 }

Advice though instead of using normal php use a framework like laravel/yii2 which makes returning data easy.不过建议不要使用普通的 php,而是使用像 laravel/yii2 这样的框架,这使得返回数据变得容易。

NB: Angular4 is a frontend framework so you cannot using echo like you would use it in a php framework.注意:Angular4 是一个前端框架,所以你不能像在 php 框架中那样使用 echo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM