Skip to content

Solutions to the Tasks

Jan Greger Hemb edited this page Sep 3, 2019 · 12 revisions

Here you can find a solution to the tasks in the Workshop. It is possible to solve it in many different ways, and the ones below are just a suggestion.

Task 1

The first steps

Task 2

The first steps

Here is the data structure: Data structure in Firestore

Task 3

The first steps

Task 4

In home.component.ts:

updateQuery() {
    this.restaurants = this.firestore.collection<Restaurant>(
      'restaurants',
      (reference => reference.where('freeDelivery', '==', true).where('averagePrice', '<', 500))
    ).valueChanges({ idField: 'id' });
  }

Bonus of adding orderBy

In home.component.ts:

  updateQuery() {
    this.restaurants = this.firestore.collection<Restaurant>(
      'restaurants',
      (reference => reference.where('freeDelivery', '==', true).where('averagePrice', '<', 500).orderBy('averagePrice'))
    ).valueChanges({ idField: 'id' });
  }

Task 4.5

In home.component.ts:

createQuery(reference: Query) {
    if (!this.searchEnabled) {
      return reference.orderBy('averagePrice', 'asc');
    }

    if (this.freeDelivery) {
      reference = reference.where('freeDelivery', '==', this.freeDelivery);
    }
    if (this.isAmerican) {
      reference = reference.where('isAmerican', '==', this.isAmerican);
    }
    reference = reference
      .where('averagePrice', '>=', this.minPrice)
      .where('averagePrice', '<=', this.maxPrice)
      .orderBy('averagePrice', 'asc');
    return reference;
  }

  updateQuery() {
    this.restaurants = this.firestore.collection<Restaurant>(
      'restaurants',
      (reference => this.createQuery(reference))
    ).valueChanges({ idField: 'id' });
  }

Task 5

Publish tutorial

Task 6

Go to the file restaurant.component.ts

  loadRestaurant() {
    this.restaurant = this.firestore.collection<Restaurant>(
      'restaurants'
    ).doc<Restaurant>(this.id).valueChanges();
  }

Task 7

Show comments

In reviews.component.ts

  ngOnInit() {
    this.reviews = this.firestore.collection<Restaurant>(
      'restaurants'
    ).doc<Restaurant>(this.id).collection<Review>('reviews').valueChanges();
  }

Add Comments

Comments data structure

In add-review.component.ts

  addReview() {
    this.firestore.collection<Restaurant>(
      'restaurants'
    ).doc<Restaurant>(this.data.id).collection<Review>('reviews').add({
      score: this.score,
      username: this.username,
      content: this.content
    }).then(() => {
      this.dialogRef.close();
    });
  }

Task ∞

Answer