abrahamlinkedin abrahamlinkedin - 22 days ago 11x
AngularJS Question

Calling arrays in Firebase using Angular 2

I would like to know how to call a Firebase array using Angular 2. In my example here, I have an array

in my Firebase DB. There are two separate iterations of
Do the dishes
, and I would like to print them out to my HTML's unordered list.

in my
private addsnotes
throws errors, and I didn't really expect otherwise. In the absence of understanding how to output the array, I am using it to illustrate what I am trying to achieve. I have also marked the relevant area where the call is being made.

My rainbow.component.html

<li *ngFor="let addsnote of addsnotes">{{addsnote}}</li>

My firebase schema:
enter image description here

My rainbow.component.ts

export class Rainbow implements OnInit{
private addsnotes: [];
private username: string;

var self = this;
var user = firebase.auth().currentUser;
var getUserInfo = firebase.database().ref('users/' + user.uid);
setTimeout(acquisition, 1000);

function acquisition(){
if (user){
getUserInfo.once('value', function(snapshot){
self.username = snapshot.val().username;
self.addsnotes = snapshot.val().addnote; //incorrect



If you want the AngularFire2 makes is easy to tune into the power of Observables so you can detect changes on the firebase end and auto-update your user notes. With AngularFire2, your solution would look more like this...


    <li *ngFor="let addsnote of addsnotes$ | async">{{ addsnote }}</li>


import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Observable } from 'rxjs/Observable';

export class RainbowComponent implements OnInit {
  private addsnotes$: Observable<string[]>;
  private username$: Observable<string>;

  constructor (
    private af: AngularFire
  ) {}

  ngOnInit () {
    let user = firebase.auth().currentUser,
        userNamePath = `users/${user.uid}/username`,
        notesPath = `users/${user.uid}/addnote`;

    this.username$ = this.af.database.object(userNamePath);
    this.addsnotes$ = this.af.database.list(notesPath);

You will need the async pipe when using Observables in your template HTML. It will auto subscribe to extract the data. The big difference with this and the previous code is that anytime your addsnotes data changes, it will automatically show the changes on the HTML view. If you want to keep it like the previous code where you are limiting it to one call using once('value'), you can add a .take(1) to the end of this.af.database.list(notesPath) to just take the list values one time.

In addition, I would recommend adding a sub field to your notes such as order so that you can sort your list in an order that you want. You can find info on how to sort with AngularFire2 here.

Hope this helps.