【问题标题】:Angular 2 : cannot read property 'push' of undefinedAngular 2:无法读取未定义的属性“推送”
【发布时间】:2017-03-31 17:45:35
【问题描述】:

在我的 Angular 2 应用程序中,我有一个函数:

notification : Array<any>;
......
......
 getNotification () {
     return setTimeout(() => {
         this.AppbankService.notify(this.user.NameId)
     .subscribe(
         (response) => {
             if (response.status === 200) {
             this.notifications.push(response.json());
             console.log(typeof(this.notifications));
              }
             this.getNotification();
         }
     )
     },5000)}

在这个函数中,我每 5 秒收到一次来自服务器的通知,并尝试将它们推送到一个数组,但是有这个:

error app.module.ts:104 error : TypeError: Cannot read property 'push' of undefined(...)

有什么建议吗?

【问题讨论】:

    标签: angularjs arrays angular


    【解决方案1】:

    改变

    notification : Array<any>;
    

    notification : Array<any> = [];
    

    【讨论】:

    • 谢谢它对我有用,但你能告诉我为什么我必须这样做吗?类型不够?
    • 不,type只指定了这个属性可以存储什么样的值,但它还没有值。使用= [],我们使用具有.push() 方法的空数组对其进行初始化。
    【解决方案2】:

    我遇到了同样的推送字符串消息问题,我的问题已通过以下代码解决。

      messages: Array<string> = [];
      add(message: string): void {
        this.messages.push(message);
    }
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,然后发现我忘记初始化我的服务方法本身,并且它的类型设置为任何。

      【讨论】:

        猜你喜欢
        • 2017-11-30
        • 2020-05-23
        • 2017-11-23
        • 1970-01-01
        • 2015-04-06
        • 2019-03-16
        • 1970-01-01
        • 2019-02-02
        • 2021-10-13
        相关资源
        最近更新 更多