База данных Firestore в реальном времени с Angular 7 - PullRequest
0 голосов
/ 28 октября 2018

Я хочу настроить простую базу данных для бронирований с использованием Firebase и базы данных в реальном времени.Я использую базу данных в реальном времени вместо нового облачного пожарного хранилища, поскольку оно позволяет мне использовать HttpClient для получения / обновления данных.До сих пор я могу сохранять бронирования в bookings.json в базе данных, а также извлекать bookings.json со всеми бронированиями внутри.Как мне поступить, если я хочу изменить внешний объект в массив при извлечении данных, установив ключ внутреннего объекта в качестве ключа массива?Это мой код:

    # HandlingService #

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HandlingService {
  constructor(private http: HttpClient) {
  }

  getBookings() {
    return this.http.get('https://...../bookings.json');
  }

  createBooking(booking) {
    return this.http.post('https://..../bookings.json', booking);
  }


}


# CreateBookingComponent #

import { Component, OnInit } from '@angular/core';
import { Booking } from 'src/app/shared/models';
import { FormGroup, FormControl } from '@angular/forms';
import { HandlingService } from 'src/app/shared/handling.service';
import { v4 as uuid } from 'uuid';

@Component({
  selector: 'app-create-booking',
  templateUrl: './create-booking.component.html',
  styleUrls: ['./create-booking.component.css']
})
export class CreateBookingComponent implements OnInit {
  booking: FormGroup;
  constructor(private handling: HandlingService) { }

  ngOnInit() {
    this.createFormGroup(new Booking());
}

  private createFormGroup(model: Booking) {
    this.booking = new FormGroup({
      id: new FormControl(uuid()),
      arrival: new FormControl(model.arrival),
      departure: new FormControl(model.departure),
      firstName: new FormControl(model.firstname),
      lastName: new FormControl(model.lastname),
      email: new FormControl(model.email),
      phone: new FormControl(model.phone),
      address: new FormControl(model.address),
      postNum: new FormControl(model.postNum),
      postPlace: new FormControl(model.postPlace),
      typeOfCabin: new FormControl(model.typeOfCabin),
    });
  }

  saveBooking() {
    const booking = <Booking>this.booking.value;
    this.handling.createBooking(booking).subscribe(err => {
      // snackbar for error here
    }, response => {
      console.log(response);
    });
  }
}


 # DashboardComponent #

 import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { HandlingService } from 'src/app/shared/handling.service';



@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

    dataSource;
    displayedColumns;

  constructor(private handling: HandlingService) { }

  ngOnInit() {
    this.displayedColumns = ['arrival', 'departure', 'name', 'phone', 'email', 'accomodation'];
    this.dataSource = new MatTableDataSource(this.mockings);
    this.handling.getBookings().subscribe(result => {
      console.log(result);
    });
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

}

# JSON-structure on Firebase realtime database #
{
  "bookings" : {
    "key" : {
      "address" : string,
      "email" : string,
      "firstName" : string,
      "id" : uuid,
      "lastName" : string,
      "phone" : string,
      "postPlace" : string
      "postNum": string,
      "arrival": date,
      "departure": date
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...