angular 5:array.length在控制台中返回undefined但是打印了数据

时间:2018-04-05 20:42:12

标签: typescript angular5

我成功地从我的本地API(laravel)获取值,并且它还将数据存储在变量中,这些变量也在视图中显示但是当我尝试获取长度或读取它以计算实时和空闲设备的数量等时它返回0(如果是长度)和未定义(访问其属性时)..以下是我的代码。我做错了什么,可以解决什么问题?

my dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserDevices } from '../../interfaces/user-devices';
import { LiveRecord } from '../../interfaces/live-record';
import { HistoryRecord } from '../../interfaces/history-record';
import { Timestamp } from 'rxjs';
import { LiveRecordModule } from '../../models/live-record/live-record.module';
import { LiveRecords } from '../../models/LiveRecords';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  user_id: number;
  token: string;
  myDevices: number[]=[];
  myLiveRecords: LiveRecord[] = [];
  myHistoryRecords: HistoryRecord[] = [];

  runningDevices: number[] =[];
  idleDevices: number[] = [];
  stoppedDevices: number[] =[];
  inactiveDevices: number[] =[];
  devicesWithNoData: number[] =[];

  constructor(private httpClient : HttpClient) { }

  ngOnInit() {
    this.user_id = +localStorage.getItem('id');
    this.token = localStorage.getItem('token');
    this.getMyDevices(this.user_id);
    console.log(this.myDevices);                        //working

    console.log(this.myLiveRecords);                    //working
    console.log(this.myHistoryRecords);                 //working

    console.log(this.myLiveRecords.length);             // 0
    console.log(this.myLiveRecords[0].deviceId);        // Error

    this.myLiveRecords.forEach(record=>{                // not working
      console.log("record found: " + record.deviceId);
    });
    for(let record in this.myLiveRecords){              // not working
      console.log(record);
    }
  }

  getMyDevices(user_id:number){
    let promise = new Promise((resolve, reject) => {
      this.httpClient.get<number[]>("http://localhost:8000/api/getMyDevices/"+this.user_id+"?token="+this.token)
        .toPromise()
        .then(
          res => { // Success
            for(let i=0; i<res.length;i++){
              this.myDevices.push(res[i]);
              this.httpClient.get<LiveRecord>("http://localhost:8000/api/getDeviceLiveRecord/"+res[i]+"?token="+this.token)
              .toPromise()
              .then(
                res => { // Success
                  if(res!=null)
                    this.myLiveRecords.push(res[0]);
                  else
                    this.myLiveRecords.push(null);
                  //console.log(res);
                  resolve();
                },
                msg => { // Error
                reject(msg);
                }
              );
              this.httpClient.get<HistoryRecord>("http://localhost:8000/api/getDeviceHistoryRecord/"+res[i]+"?token="+this.token)
              .toPromise()
              .then(
                res => { // Success
                  if(res !=null)
                    this.myHistoryRecords.push(res[0]);
                  else
                    this.myHistoryRecords.push(null);
                  //console.log(res);
                  resolve();
                },
                msg => { // Error
                reject(msg);
                }
              );
            }
            resolve();
          },
          msg => { // Error
          reject(msg);
          }
        );
    });
    return promise;    
  }
}

my dashboard.component.html

<div class="deviceInfo">
    <div class="row">
        <div class="col-md-2" style="background:green; height:50px">
            <span>Running</span>
        </div>
        <div class="col-md-2" style="background:yellow; height:50px">
            <span>Idle</span>
        </div>
        <div class="col-md-2" style="background:red; height:50px">
            <span>Stopped</span>
        </div>
        <div class="col-md-2" style="background:grey; height:50px">
            <span>Inactive</span>
        </div>
        <div class="col-md-2" style="background:black; height:50px">
            <span>No Data</span>
            <p>{{devicesWithNoData.length}}</p>
        </div>
    </div>
</div>
<div class="row">
    <table>
        <thead>
            <td>S.N</td>
            <td>DeviceID</td>
            <td>Last Live</td>
        </thead>
        <tbody>
            <tr *ngFor="let live of myLiveRecords;let i =index">
                <td>{{i+1}}</td>
                <td>{{live?.deviceId?live.deviceId:myDevices[i]}}</td>
                <td>{{live?.recordDate?live.recordDate:"No Data"}}</td>
            </tr>

        </tbody>
    </table>
</div>

这就是我在浏览器中获得的内容 output with console

1 个答案:

答案 0 :(得分:0)

enter image description here问题出在里面。

{{live?.deviceId?live.deviceId:myDevices [i]}}&lt; --- Ternary?

你在哪里声明deviceId?像var或let deviceId = xxxxx;  在Google中添加一个手表以查看此变量是否存在。

这里不容易找到。你应该用JavaScript 6或5编写它的typeScript。

相关问题