2016-08-13 23 views
5

Tôi nhận được lỗi TypeError này: Không thể đọc thuộc 'chạy' không xác định trong Subscriber.js: 229 và không biết lý do tại sao - trong ionic beta 10 mã này hoạt động tốt ... trong 11 không.NgZone/Angular2/Ionic2 Lỗi Loại: Không thể đọc thuộc 'chạy' không xác định

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 = ''; 
    } 
} 

Trả lời

8

Thay vì tiêm nó như thế này:

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

Tại sao bạn không làm điều đó như thế này:

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); 
    }); 
    } 
} 

tôi thêm private zone: NgZone như một tham số trong constructor và sau đó tôi có thể sử dụng phương pháp run() bằng cách sử dụng biến số zone như sau:

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

Tiết kiệm thời gian của tôi! Cảm ơn bạn, bây giờ nó hoạt động tuyệt vời! – Patrick1870

Các vấn đề liên quan