【问题标题】:Get the length of the Observable [duplicate]获取 Observable 的长度 [重复]
【发布时间】:2017-08-03 17:09:02
【问题描述】:
export class AppComponent { 

  posts: any[];
  requestStream: any;

    constructor(http: Http){  
       http.get('https://api.github.com/users')
         .subscribe(  
         response => { this.posts = response.json(); });  
    }  
}

还有:

<div *ngFor="let post of posts">
{{ post.login }}
</div>
{{ posts.length }}

视图很好地显示了所有内容 - 每个帖子的登录名和帖子的长度(为 30),但控制台给出错误:

无法读取未定义的属性“长度”

还有一个问题是该 url (https://api.github.com/users) 实际上包含的记录多于 30 (46) 个。那么为什么我只得到 30 条记录呢?

【问题讨论】:

  • 在插值中添加安全导航运算符:{{ posts?.length }}。你怎么知道你有 46 个帖子?你检查过网络标签吗?
  • 啊...对,忘记了 Elvis 运算符...但是请检查我的其他问题 - 为什么我只得到 30 条记录,而有 46 条...?
  • 你怎么知道你有 46 条记录?
  • 对不起,我的错。非常抱歉
  • 我刚刚检查了第一个 id 为 1 的,以及最新的 id46...

标签: angular rxjs


【解决方案1】:

错误发生在http 获取数据之前,您的帖子值未定义。要解决这个问题,您需要在声明帖子时对其进行初始化。

posts = [];

或者在你的模板中你可以使用

{{ posts?.length }}

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2018-03-19
    • 2011-07-28
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2018-08-09
    相关资源
    最近更新 更多