2016-08-13 9 views
5

Otrzymuję ten błąd TypeError: Nie można odczytać właściwości 'run' z undefined w pliku Subscriber.js: 229 i nie wiem dlaczego - in ionic beta 10 ten kod działa dobrze ... w 11 nie.NgZone/Angular2/Ionic2 TypeError: Nie można odczytać właściwości 'run' z undefined

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

Odpowiedz

8

Zamiast wstrzykiwanie go tak:

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

Dlaczego nie zrobić tak:

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

Dodaję private zone: NgZone jako parametr w constructor i następnie można użyć metody run() za pomocą zmiennej zone w następujący sposób:

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

Zaoszczędź mój czas! Dziękuję, teraz działa świetnie! – Patrick1870