【问题标题】:angular 5: array.length returning undefined in console but data are printed角度 5:array.length 在控制台中返回未定义但打印数据
【发布时间】:2018-09-15 19:07:36
【问题描述】:

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

我的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;    
  }
}

我的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

【问题讨论】:

    标签: typescript angular5


    【解决方案1】:

    问题在里面。

    {{live?.deviceId?live.deviceId:myDevices[i]}}

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

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

    【讨论】:

    • 请看问题最后的图片。deviceId是存储在myLiveRecords中的属性。那段代码工作正常..问题是我无法访问dashboard.component.ts文件中的myLiveRecords.length或myLiveRecords[0].deviceId
    • 我猜你没有通过单击带有控制台链接的输出来检查问题最后的图片..上面的链接没有提供我的解决方案
    • 我在 Chrome 中使用 watch 来查看变量是否存在 Put add warch this.myLiveRecords 或 this.-> record.deviceId this.myLiveRecords[0].deviceId
    • in JS DashboardComponent.prototype.ngOnInit = function () { console.log(this.myLiveRecords[0].deviceId); // 错误 this.myLiveRecords.forEach(function (record) { console.log("record found: " + record.deviceId); }); for (var record in this.myLiveRecords) { // 不工作 console.log(record); } };
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2016-03-11
    相关资源
    最近更新 更多