【问题标题】:NgZone/Angular2/Ionic2 TypeError: Cannot read property 'run' of undefinedNgZone/Angular2/Ionic2 TypeError:无法读取未定义的属性“运行”
【发布时间】:2016-12-20 15:02:27
【问题描述】:

我收到此错误 TypeError: Cannot read property 'run' of undefined in Subscriber.js:229 并且不知道为什么 - 在 ionic beta 10 中,此代码运行良好...在 11 没有。

import {Component, NgZone} from '@angular/core';
import {NavController} from 'ionic-angular';

declare var io;

@Component({
  templateUrl: 'build/pages/home/home.html'
})    
export class HomePage {
    static get parameters() {
        return [NgZone];
    }

    zone: any;
    chats: any;
    chatinp: any;
    socket: any;

constructor(public navCtrl: NavController, ngzone) {
    this.zone = ngzone;
    this.chats = [];
    this.chatinp ='';
    this.socket = io('http://localhost:3000');
    this.socket.on('message', (msg) => {
        this.zone.run(() => {
            this.chats.push(msg);
        });
    });
}

send(msg) {
    if(msg != ''){
        this.socket.emit('message', msg);
    }
    this.chatinp = '';
   }
}

【问题讨论】:

    标签: angular typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    而不是像这样注入它:

    static get parameters() {
      return [NgZone];
    }
    

    你为什么不这样做:

    import { Component, NgZone } from "@angular/core";
    
    @Component({
      templateUrl:"home.html"
    })
    export class HomePage {
    
      public chats: any;
    
      constructor(private zone: NgZone) {
    
        this.chats = [];
        let index: number = 1;
    
        // Even though this would work without using Zones, the idea is to simulate
        // a message from a socket.
        setInterval(() => { this.addNewChat('Message ' + index++); }, 1000);
      }
    
      private addNewChat(message) {
        this.zone.run(() => {
            this.chats.push(message);
        });
      }
    }
    

    我将private zone: NgZone 添加为constructor 中的参数,然后我可以通过使用zone 变量来使用run() 方法,如下所示:

    this.zone.run(() => {
      // ... your code
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多