0

Sorry for the long question. I have a list of events which I get like this:

export class HomePageComponent implements OnInit {

  events: FirebaseListObservable<EventModel[]>;

  constructor(
    private authService: AuthService,
    private router: Router,
    private db: AngularFireDatabase
  ) {
    this.events = db.list('/events');
  }

  ngOnInit() {
  }

}

Events are displayed like this:

<md-card *ngFor="let event of events | async">
    <a [routerLink]="['event', event.slug]"><img class="event-img" src="http://lorempixel.com/30/30" />{{ event.name }}</a>
</md-card>

The event.component looks like this:

export class EventComponent implements OnInit {

  event: Object;
  name: String;

  constructor(db: AngularFireDatabase, route: Router) {

    const eventQuery = db.list('/events', {
      query: {
        orderByChild: 'slug',
        equalTo: 'event-name'
      }
    }).subscribe(data => {
      this.event = data[0];
    });

  }

  ngOnInit() {
  }

}

this.event is complete and the correct information is being queried. It looks like this:

Object {category: "category", description: "description", googleMap: "map", guests: Object, name: "Event name"…}
category: "category"
description: "description"
googleMap: "map"
guests: Object
name: "Event name"
slug: "event-name"
venue: "The venue"
$exists: function ()
$key: "-xxxxxxxx"
__proto__: Object

When I try to display the name {{event.name}} I get an error

ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer]

Additional question:

Since the event information already exists in HomePageComponent, can it be sent to EventComponent and used to display the event? Maybe this will avoid an additional database query.

1 Answer 1

1

Use safe operator ?

<md-card *ngFor="let event of events | async">
    <a [routerLink]="['event', event?.slug]"><img class="event-img" src="http://lorempixel.com/30/30" />{{ event?.name }}</a>
</md-card>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi. Thank you for answering. I added the safe operator to the event.component.html and it worked. I don't have any errors in the homepage.component.html where the link is. So that works. Did you notice my additional question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.