Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, callback doesn't change variable

I have the following snippet

This is my main.html

<h2 class="txtcenter po-2text" style="padding-top:30px">
    {{title}}
</h2>

This is my main.ts:

title: string;

ngOnInit() {
    var self = this;
    var ref = firebase.database().ref('schools/' + this.currentUserId());
    ref.orderByChild('title').on('value', function(dataSnapshot) {
        console.log("Title is: " + dataSnapshot.val().title);
        self.title = dataSnapshot.val().title;
    });
}

Even though the callback gets fired with some valid data, the title doesn't update automatically. What am I missing?

Any help is appreciated!

like image 629
Luigi Capogrosso Avatar asked Mar 05 '23 07:03

Luigi Capogrosso


1 Answers

Angular change detection works based on browser events, since this is a fire base event callback this wont trigger the change detection. So try the following

Import NgZone:

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

Add it to your class constructor

constructor(public zone: NgZone, ...args){}

Run code with zone.run:

ref.orderByChild('title').on('value', (dataSnapshot) => {
        console.log("Title is: " + dataSnapshot.val().title);
        this.zone.run(() => this.title = dataSnapshot.val().title;)
});
like image 115
Anto Antony Avatar answered Mar 15 '23 01:03

Anto Antony