使用API​​(https)时如何获取数组的长度?

时间:2018-10-06 14:02:54

标签: angular api

getDepartments(): void {
    this.departmentService.getDepartments().
   subscribe(departments => this.departments = departments);
    //   subscribe(data => this.departments = data);
  }
  getNumDep():void{
    this.depNumber = this.departments.length;

当前,我有这个,我需要更改getNumDep方法以从数据库中获取数据。现在,它不计算数组的长度,我得到了这个异常:

  

无法读取未定义的属性“ length”
  在DashboardComponent.push ../ src / app / dashboard / dashboard.component.ts.DashboardComponent.getNumDep(dashboard.component.ts:59)

1 个答案:

答案 0 :(得分:0)

departmentService.getDepartments()是异步的,因此,如果在返回值之前调用getNumDep(),则会收到该错误。通常,让getNumDep()这样的方法(如果提早调用)将引发异常是一个坏主意。相反,我建议将长度分配给订阅中的变量,例如@ghuntheur也建议:

import { throwError } from 'rxjs';  // If you're using rxjs6


getDepartments(): void {
    this.departmentService.getDepartments().
    subscribe(departments => {
        if (departments) {
            this.departments = departments;
            this.depNumber = departments.length;
            this.depNumNotEindhoven = departments.filter(dep => dep.location !== 'Eindhoven').length;
        }
        else {
            Observable.throw("Error: Service didn't return an object")  // If you're using rxjs <6
            throwError("Error: Service didn't return an object");  // If you're using rxjs6
        }
    });
}

进行此更改,然后完全删除getNumDep()。然后,当需要获取长度时,可以从this.depNumber变量中访问它。

编辑:作为一个旁注,约定是get ...()方法应返回当前值。您的getNumDep()通过设置值来执行相反的操作。为避免混淆,如果决定保留该方法,建议您将方法的名称更改为setNumDep()。