Firebase - 检索单个对象

时间:2017-06-17 20:05:50

标签: angular typescript firebase-realtime-database

很抱歉这个问题很长。我有一个事件列表,我得到这样的结果:

export class HomePageComponent implements OnInit {

  events: FirebaseListObservable<EventModel[]>;

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

  ngOnInit() {
  }

}

事件显示如下:

<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>

event.component看起来像这样:

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已完成,正在查询正确的信息。它看起来像这样:

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

当我尝试显示名称{{event.name}}时出现错误

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

其他问题:

由于HomePageComponent中已存在事件信息,是否可以将其发送到EventComponent并用于显示事件?也许这会避免额外的数据库查询。

1 个答案:

答案 0 :(得分:1)

使用安全操作符 ?

<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>