Search code examples
javascriptangularangularfire2angular2-observables

Trying to add a property to an object inside observable


Pretty straightforward situation as per the title, trying to add the attendingType property to an event object, if the person is attending (so I can change status in view).

Other notes, Im working with Angularfire 2 and the data returned is an observable array of Event[]. When I change the return to return (console.log({ ...event, attendingType: currentUser.type } as eventWithAttendance)); it prints the additional property fine.

Here is the interface

export interface Event {
  schoolId: string;
  eventId: string;
  name: string;
  date: Date;
  timeStart: number;
  timeEnd: number;
  volunteersRequired: boolean;
  attendance?: Array<EventUser>;
  imageUrl: string;
  contactName: string;
  contactPhone: number;
  contactEmail: string;
  description: string;
}

export interface EventUser {
  id: string;
  email: string;
  name: string;
  type: ATTENDANCE;
}

export enum ATTENDANCE {
  attending = 'attending',
  notAttending = 'notAttending',
  volunteering = 'volunteering'
}

and here is the code for the ts file

interface eventWithAttendance extends Event {
  attendingType: ATTENDANCE;
}

ionViewDidLoad() {
    this.activeSchool = this.data.activeSchool;

    //this.events = this.data.getEvents(this.activeSchool.schoolId).pipe();

    this.auth.user.subscribe((user) => {
      this.user = user;
    });

    this.events = this.data.getEvents(this.activeSchool.schoolId)
      .pipe(
        map((events) => {
            events.map( (event) => {
              let currentUser = event.attendance.find(user => user.id === this.user.uid);
              if(currentUser) {
                return ({ ...event, attendingType: currentUser.type } as eventWithAttendance);
              } else {
                return event;
              }
            });

          return events as eventWithAttendance[];
        })
      );


    // Not a long term solution
    this.currentDate = new Date().getTime(); // so we don't display old events
  }

Solution

  • The problem is that .map on an array does not change the original array, but it returns a new array.

    So if you change:

    events.map( (event) => {
    

    To:

    const updatedEvents = events.map( (event) => {
    

    And then change the return statement to:

    return updatedEvents as eventWithAttendance[];