【问题标题】:TypeError: Cannot read property 'length' (typescript/Observable/angular2)TypeError:无法读取属性“长度”(打字稿/Observable/angular2)
【发布时间】:2016-07-30 13:53:02
【问题描述】:

我想做的很简单,我有一个函数getListData,它返回Person[] 的Observable,我想将它作为Person[] 传递给html。

所以我这样做了:

 @Injectable()
  export class AppCmp implements OnInit {

    listToDisplay: Person[];

    showingPerson = false;

    constructor(private _myService: MyService) {
    };

    public showMatcherData(): void {
      this.showingPerson = true;
      this. _myService.getListData().subscribe(res => {
        this.listToDisplay = res;
      })
    }

但我得到一个错误:

异常:类型错误:无法读取未定义的属性“长度” [AppCmp@41:60 中的列表显示]

这是我在登录 listToDisplay 时得到的:

这就是我展示它的方式:

<div *ngIf="showingPerson">
    <div dnd-sortable-container  [dropZones]="['zone-one']" [sortableData]="listToDisplay">
      <div class="list-bg" *ngFor="#per of listToDisplay; #i = index" dnd-sortable [sortableIndex]="i">
        ID: {{per.id}} <p></p> age: {{per.age}}
      </div>
    </div>
  </div>

如果我使用的是 person2:

let person2 = () => {
  return  [
    {
      "id": "2323",
      "age": 22
    },
    {
     "id": "2323",
      "age": 22
    }
    ,
    {
     "id": "2323",
      "age": 22
    }
  ]

};

而不是 listToDisplay 它可以工作,为什么?

这是什么意思,我该如何解决?

【问题讨论】:

  • 1) 删除 injectable() 行。 2) 确保ngOnInit 已实现 3) 如果仍然无法正常工作,请显示getListData() 代码。 4)html 也可能有问题。
  • 我需要可注入并实现了ngOnInIt,我只是发送了我的代码的简化
  • 您是否在this.listToDisplay 中获取数据?签入控制台。
  • 是的,兄弟刚刚添加了日志的屏幕截图@micronyks
  • 还需要 hTML 部分来显示您的对象列表。

标签: typescript angular observable reactivex


【解决方案1】:

问题可能与这个sortableData有关:

<div dnd-sortable-container  [dropZones]="['zone-one']" [sortableData]="listToDisplay">

而不是*ngFor

您应该只显示整个内容:

<div *ngIf="showingPerson">

(也就是说,更改*ngIf 处的标志)加载数据之后,而不是像现在这样之前。

所以这个:

public showMatcherData(): void {
  this.showingPerson = true;   // <------------------------------ line will move
  this. _myService.getListData().subscribe(res => {
    this.listToDisplay = res;
  })
}

应该变成:

public showMatcherData(): void {
  this. _myService.getListData().subscribe(res => {
    this.listToDisplay = res;
    this.showingPerson = true; // <------------------------------ line moved
  })
}

【讨论】:

    猜你喜欢
    • 2019-10-16
    • 1970-01-01
    • 2016-11-14
    • 2017-12-26
    • 2019-01-31
    • 1970-01-01
    • 2018-03-27
    • 2020-06-12
    相关资源
    最近更新 更多