【问题标题】:How to get json data to an angular array variable如何将json数据获取到角度数组变量
【发布时间】:2020-03-06 09:31:09
【问题描述】:

我正在尝试将 json 结果传递给数组对象。我在 php 中回显 json 数据。像这样。

    <?php
header('Access-Control-Allow-Origin: *');
header('Content-type:application/json;charset=utf-8');
$arr=  '[{
   "id": "1",
   "date": "2020-03-21",
   "status": "present",
   "studentid": "1"
  },
  {
   "id": "2",
   "date": "2020-03-24",
   "status": "present",
   "studentid": "1"
  },
  {
   "id": "3",
   "date": "2020-03-25",
   "status": "absent",
   "studentid": "1"
  },
  {
   "id": "4",
   "date": "2020-03-26",
   "status": "absent",
   "studentid": "1"
  }
 ]';

echo $arr;
?>

~


如何在数组中使用角度来获取缺勤者。

我试过的角部分没用

      this.http.post("http://localhost/android/Api.php?apicall=getattendance", JSON.stringify(this.postData),options)


          .subscribe( (data) => {
          this.setUsersArray(data);
          console.log(data + "URL DATA"+JSON.stringify(this.postData));

           }


      );

=====================================================================
    setUsersArray(data){

       if (data instanceof Array) {
                       {

                        this.date_present = data.map(function (ele) {
                        if(ele.status==='present')
                        {

                          return ele.date;

                        }



                        });
                        this.date_absent = data.map(function (ele) {
                          if(ele.status==='absent')


                          return ele.date;

                          });
                   }
                    }

我将 date_absent 和 date_present 设为 null。为什么我将其设为 null。请帮助我。我是 Angular 新手。

【问题讨论】:

  • 看起来你的 if 块在订阅之外?所以你可能无权访问数据。
  • 实际上该部分在函数 setUsersArray(data);
  • @sam 很抱歉这个错误。我已经更正了
  • 也许您不想为此使用 map ,因为 map 将为您正在循环的数组中的每个项目返回一些内容。所以对于this.date_present ,我希望您的数据看起来像 ["2020-03-21", "2020-03-24", undefined, undefined];您可以改用 forEach 来避免这种情况,并将值推送到数组 this.date_present 。此外,您的数组看起来像一个字符串,这可能是您目前无法使用它的原因,请尝试在 if 块中抛出一个调试器并查看它是否被调用。

标签: php json angular


【解决方案1】:

在打字稿中尝试 for 循环

setUsersArray(data:any){
for(let item of data){
  console.log(item);
  if(item.status==='present') {
    this.present.push(item.date);
  }
  if(item.status==='absent') {
    this.absent.push(item.date);
  }       
}

【讨论】:

    【解决方案2】:

    尝试访问此网址 $characters = json_decode($data, true); // 解码 JSON 提要并创建一个关联数组 https://www.taniarascia.com/how-to-use-json-data-with-php-or-javascript/

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 2017-09-22
      • 2019-03-21
      • 2019-03-16
      • 2021-11-11
      • 1970-01-01
      • 2015-09-22
      • 2018-04-01
      相关资源
      最近更新 更多