I have a service that fetches some objects via firebase. It then populates an array which should then prompt angular to update the DOM with an *ngFor statement, but it doesn't work. Code as follows:
TeachersService
import {Injectable} from 'angular2/core';
import {Teacher} from './teacher.ts';
@Injectable()
export class TeachersService {
private firebaseURL: string;
private teachersRef: Firebase;
constructor() {
this.firebaseURL = "https://xyz.firebaseio.com/teachers";
this.teachersRef = new Firebase(this.firebaseURL);
}
getTeachers() {
this.teachersRef.on("value", function(snapshot) {
var tempArr = new Array(snapshot.numChildren());
// this.teachers = snapshot.val();
snapshot.forEach(function(data) {
var teacher = {
name: data.key(),
position: data.val().stilling
}
tempArr.push(teacher);
});
// this.teachers = tempArr;
console.log(tempArr);
return Promise.resolve(tempArr);
});
return Promise.resolve([]);
}
}
And Teachers
import {Component, AfterViewInit, OnInit, View} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {Router} from 'angular2/router';
import {TeachersService} from '../../services/teachers.service';
@Component({
selector: 'teachers',
templateUrl: './components/teachers/teachers.html',
providers: [TeachersService]
})
export class TeachersCmp implements AfterViewInit, OnInit {
private firebaseURL: string;
private teachersRef: Firebase;
public teachers: Array<any>;
constructor(
private _router: Router,
private _teachersService: TeachersService
) {}
ngOnInit() {
this.populateTeachersArr();
}
populateTeachersArr() {
this._teachersService.getTeachers().then(teachers => this.teachers = teachers);
}
}
Teachers.html
<ul>
<li *ngFor="#teacher of teachers">
<strong>{{teacher.name}}</strong>: {{teacher.position}}
</li>
I suspect this has to do with change detection (or at least my understanding of it). But I don't know how to prompt ng2 to detect the array update. If I create a static array like: [1,2,3,4]
the *ngFor statement correctly works and displays it like it should in the DOM.