Использование NgZone для обновления вида компонента - PullRequest
0 голосов
/ 28 апреля 2018

У меня есть структура компонента как

-stats
 -stats.component.ts
 -stats.component.html
 -stats.component.css

Мне нужно обновить объект myData в файле stats.component.ts / html , используя NgZone, чтобы при обновлении rpm, скорости или любого значения в консоли Firebase это отражалось в представлении компонентов в мое приложение на нативном языке. Я хочу, чтобы объект result.value в функции монитора в firebase.service.ts сохранялся в объекте mydata.

Скриншот консоли Firebase

stats.component.html

<ActionBar title="Car Statistics">

</ActionBar>


<GridLayout class="paramsView" rows="auto,auto,auto,auto,auto" columns="*,*" width="auto" height="500" backgroundColor="red" >
         <Label row="0" col="0" class="h3" text="Name: " textWrap="true"></Label>        
        <Label row="0" col="1" class="h3" [text]="mydata.name" textWrap="true"></Label>

        <Label row="1" col="0" class="h3" text="RPM: " textWrap="true"></Label>        
        <Label row="1" col="1" class="h3" [text]="mydata.rpm" textWrap="true"></Label>

        <Label row="2" col="0" class="h3" text="Vehicle Speed: " textWrap="true"></Label>        
        <Label row="2" col="1" class="h3" [text]="mydata.speed" textWrap="true"></Label>

        <Label row="3" col="0" class="h3" text="Coolant Temperature: " textWrap="true"></Label>        
        <Label row="3" col="1" class="h3" [text]="mydata.coolantTemp" textWrap="true"></Label>

        <!-- <Label row="4" col="0" class="h3" text="Coolant Temperature: " textWrap="true"></Label> -->
        <Label row="4" col="1" class="h3" [text]="mydata.value" textWrap="true"></Label>


</GridLayout>

stats.component.ts

import { Component, OnInit,Inject, NgZone, DoCheck  } from '@angular/core';
import {registerElement} from 'nativescript-angular/element-registry';
import {DataService} from "../services/firebase.service";
import * as firebase from "nativescript-plugin-firebase";



@Component({
    moduleId:module.id,
    templateUrl: "./stats.component.html",
    styleUrls: ['stats.component.css']
})


export class StatsComponent implements OnInit, DoCheck {

    private mydata;
    private val;


    constructor(private dataService:DataService,
     private zone: NgZone

    ){

    }

    ngOnInit(){

        this.dataService.firebaseInit();

        Here i will call the value/childListener from my firebase.service.ts;
        this.dataService.monitor();

    }

    ngDoCheck() {
        console.log("Change detection encountered!")
    }




}

firebase.service.ts

import { Injectable, NgZone } from "@angular/core";
import { Observable as RxObservable } from "rxjs/Observable";
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/do";
import * as firebase from "nativescript-plugin-firebase";


@Injectable()
export class DataService {

    constructor(

    ) { }

    firebaseInit() {

        return firebase.init({
        }).then(
            () => {
                // console.log("initialized");

            }
            ).catch(
            (err) => { console.log("Error is: " + err) }
            )

    }



  monitor(){
            let str = '5C:CF:7F:B3:07:0E/17-04-2018/11-35/';
            var onValueEvent = function (result) {         

                 console.log("Event type: " + result.type);
                 console.log("Key: " + result.key);
                 console.log("Value: " + JSON.stringify(result.value));
                 JSON.stringify(result.value);
            };
            return firebase.addValueEventListener(onValueEvent, '/CarData/'+ str).then(
                function (listenerWrapper) {
                    var path = listenerWrapper.path;
                    var listeners = listenerWrapper.listeners; // an Array of listeners added
                    // you can store the wrapper somewhere to later call 'removeEventListeners'
                }
            );

     }

1 Ответ

0 голосов
/ 22 мая 2018

Вы можете передать функцию обратного вызова напрямую в функцию firebase.motitor. и когда он вызывается, вы можете присвоить result.value переменной mydata внутри zone.run().

stats.component.html

<ActionBar title="Car Statistics">

</ActionBar>


<GridLayout class="paramsView" rows="auto,auto,auto,auto,auto" columns="*,*" width="auto" height="500" backgroundColor="red" >
         <Label row="0" col="0" class="h3" text="Name: " textWrap="true"></Label>        
        <Label row="0" col="1" class="h3" [text]="mydata.name" textWrap="true"></Label>

        <Label row="1" col="0" class="h3" text="RPM: " textWrap="true"></Label>        
        <Label row="1" col="1" class="h3" [text]="mydata.rpm" textWrap="true"></Label>

        <Label row="2" col="0" class="h3" text="Vehicle Speed: " textWrap="true"></Label>        
        <Label row="2" col="1" class="h3" [text]="mydata.speed" textWrap="true"></Label>

        <Label row="3" col="0" class="h3" text="Coolant Temperature: " textWrap="true"></Label>        
        <Label row="3" col="1" class="h3" [text]="mydata.coolantTemp" textWrap="true"></Label>

        <!-- <Label row="4" col="0" class="h3" text="Coolant Temperature: " textWrap="true"></Label> -->
        <Label row="4" col="1" class="h3" [text]="mydata.value" textWrap="true"></Label>


</GridLayout>

stats.component.ts

import { Component, OnInit,Inject, NgZone, DoCheck  } from '@angular/core';
import {registerElement} from 'nativescript-angular/element-registry';
import {DataService} from "../services/firebase.service";
import * as firebase from "nativescript-plugin-firebase";



@Component({
    moduleId:module.id,
    templateUrl: "./stats.component.html",
    styleUrls: ['stats.component.css']
})


export class StatsComponent implements OnInit, DoCheck {

    private mydata;
    private val;


    constructor(private dataService:DataService,
     private zone: NgZone

    ){

    }

    ngOnInit(){

        this.dataService.firebaseInit();

        Here i will call the value/childListener from my firebase.service.ts;
        this.dataService.monitor((result)=>{
            console.log("Event type: " + result.type);
             console.log("Key: " + result.key);
             console.log("Value: " + JSON.stringify(result.value));
             this.zone.run(()=>{
                 this.mydata=JSON.stringify(result.value);                     
             });

        });

    }

    ngDoCheck() {
        console.log("Change detection encountered!")
    }




}

firebase.service.ts

import { Injectable, NgZone } from "@angular/core";
import { Observable as RxObservable } from "rxjs/Observable";
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/do";
import * as firebase from "nativescript-plugin-firebase";


@Injectable()
export class DataService {

    constructor(

    ) { }

    firebaseInit() {

        return firebase.init({
        }).then(
            () => {
                // console.log("initialized");

            }
            ).catch(
            (err) => { console.log("Error is: " + err) }
            )

    }



  monitor(onValueEvent){
            let str = '5C:CF:7F:B3:07:0E/17-04-2018/11-35/';
            return firebase.addValueEventListener(onValueEvent, '/CarData/'+ str).then(
                function (listenerWrapper) {
                    var path = listenerWrapper.path;
                    var listeners = listenerWrapper.listeners; // an Array of listeners added
                    // you can store the wrapper somewhere to later call 'removeEventListeners'
                }
            );

     }
...