Seysay
Seysay

Reputation: 13

Display data after subscribe from firebase snapshot

I'm struggling with rxjs.. I would like to sort an array coming from my subscription. But the sort never play.. SO first I tried to display userBirthdayDate from service but didn't work like expected.

this is my service

 getAllUsers() {
    return new Promise((resolve, reject) => {
      firebase
        .database()
        .ref()
        .child('users')
        .on(
          'value',
          snapshot => {
            resolve(
              snapshot.forEach(childSnapshot => {
                this.usersBirthday = childSnapshot.val()
                  ? childSnapshot.val()
                  : [];
                this.emitBirthday();
              })
            );
          },
          error => {
            reject(error);
          }
        );
    });
  }

my component.ts

export class WidgetBirthdayComponent implements OnInit {
  users: User[];
  usersBirthdayDate = [];
  usersSubscription: Subscription;

  constructor(private userService: UsersService) {}

  ngOnInit() {
    // this.usersSubscription = this.userService.birthdaySubject.subscribe(
    //   test => {
    //     this.usersBirthdayDate.push(test);
    //   }
    // );
    // this.userService.emitBirthday();
    // this.userService.getAllUsers();

    const myArray = [
      {
        name: "Joel",
        birthdayDate: "Wednesday, November 25, 1992"
      },
      {
        name: "Sarah",
        birthdayDate: "Thursday, April 16, 1992"
      },
      {
        name: "Beverly",
        birthdayDate: "Thursday, February 26, 1998"
      }
    ];

    myArray.sort(function compare(a, b) {
      const now = new Date();
      const dateA = new Date(a.birthdayDate);
      dateA.setFullYear(now.getFullYear());
      if (dateA.getTime() - now.getTime() < 0) {
        dateA.setFullYear(now.getFullYear() + 1);
      }
      const dateB = new Date(b.birthdayDate);
      dateA.setFullYear(new Date().getFullYear());
      dateA.setFullYear(now.getFullYear());
      if (dateB.getTime() - now.getTime() < 0) {
        dateB.setFullYear(now.getFullYear() + 1);
      }
      return dateA.getTime() - dateB.getTime();
    });
    console.log(myArray);
  }

So I tried with strong data and my function sort is working well.. but I can"t use usersBirthdayDate[] on it.. PLease need help :)

Upvotes: 0

Views: 460

Answers (2)

Seysay
Seysay

Reputation: 13

So this is my component.ts

I'm getting this on my console :

an array with the three elements inside my database 

1: {birthdayDate: "Thursday, April 16, 1992", firstName: "Sarah", lastName: "Doe", photoUrl: "https://firebasestorage.googleapis.com/v0/b/dashbo…=media&token=9a2ee641-e5ee-4be5-827c-8369903a04ec"}
2: {birthdayDate: "Wednesday, November 25, 1992", firstName: "Thomas", lastName: "Loe", photoUrl: "https://firebasestorage.googleapis.com/v0/b/dashbo…=media&token=6736f24b-7c60-4722-9fad-9a8e73cc0e0a"}
3: {birthdayDate: "Thursday, February 26, 1998", firstName: "Sophie", lastName: "test", photoUrl: "https://firebasestorage.googleapis.com/v0/b/dashbo…=media&token=8ff30a9d-c644-4df6-8ecb-243121ccd7de"}
    length: 4

but the function sort still doesn't work cause I have to get same array with Sophie first and sarah and Thomas. And when I tried with same data direct in component, the function is working well..

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../services/users.service';
import { User } from '../../models/user';
import { Subscription } from 'rxjs';


@Component({
  selector: 'app-widget-birthday',
  templateUrl: './widget-birthday.component.html',
  styleUrls: ['./widget-birthday.component.scss']
})
export class WidgetBirthdayComponent implements OnInit {
  users: User[];
  usersBirthdayDate = [];
  usersSubscription: Subscription;

  constructor(private userService: UsersService) {}

  ngOnInit() {
    this.usersSubscription = this.userService.birthdaySubject.subscribe(
      test => {
        this.usersBirthdayDate.push(test);
        this.usersBirthdayDate.sort(function compare(a, b) {
          const now = new Date();
          const dateA = new Date(a.birthdayDate);

          dateA.setFullYear(now.getFullYear());
          if (dateA.getTime() - now.getTime() < 0) {
            dateA.setFullYear(now.getFullYear() + 1);
          }
          const dateB = new Date(b.birthdayDate);
          dateA.setFullYear(new Date().getFullYear());
          dateA.setFullYear(now.getFullYear());
          if (dateB.getTime() - now.getTime() < 0) {
            dateB.setFullYear(now.getFullYear() + 1);
          }
          return dateA.getTime() - dateB.getTime();
        });
        console.log(this.usersBirthdayDate);
      }
    );
    this.userService.emitBirthday();
    this.userService.getAllUsers();

    // const myArray = [
    //   {
    //     name: 'Thomas',
    //     birthdayDate: 'Wednesday, November 25, 1992'
    //   },
    //   {
    //     name: 'Sarah',
    //     birthdayDate: 'Thursday, April 16, 1992'
    //   },
    //   {
    //     name: 'Sophie',
    //     birthdayDate: 'Thursday, February 26, 1998'
    //   }
    // ];
  }
}

service.ts

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
import { User } from '../models/user';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UsersService {
  users: User[] = [];
  usersSubject = new Subject<User[]>();
  birthdaySubject = new Subject<User[]>();
  usersBirthday: User[] = [];

  constructor() {}

  emitUsers() {
    this.usersSubject.next(this.users);
  }

  emitBirthday() {
    this.birthdaySubject.next(this.usersBirthday);
  }



  getAllUsers() {
    firebase
      .database()
      .ref()
      .child('users')
      .on('value', snapshot => {
        this.usersBirthday = snapshot.val()
          ? snapshot.val()
          : console.log('oro');
        this.emitBirthday();
      });
  }
}

Upvotes: 0

Eric Mallard
Eric Mallard

Reputation: 51

In case you tried to sort the array outside the subscription (like in your snippet of code), it is not working because, when your code runs, you only sort the array once in the ngOnInit hook. By then, your observable hasn't emitted any userBirthday yet. So the usersBirthdayDate array is empty.

I'm not sure where/when you are trying to make you sort happen but have you tried something like the following:

this.usersSubscription = this.userService.birthdaySubject.subscribe(
    test => {
        this.usersBirthdayDate.push(test);
        this.usersBirthdayDate.sort(yourSortingFunction);
    }
);

If that does not work maybe you could explain a bit more what happens in your subscription when you receive a new user? Then I'll be able to edit my answer if needed.

Upvotes: 1

Related Questions