Home > database >  get value from observable to use it in component.ts - Angular
get value from observable to use it in component.ts - Angular

Time:06-14

During an Angular course we build kinda hotel reservation system with Angular. The application is quite simple with basic CRUD functions and each reservation has an ID, name, room number, arrival- and departure date. The data is fetched with an InMemory Web-API.

I struggle with setting the Booking ID based on the highes existing one and increment it by 1. If the latest booking (based on the creation date) has ID 111, an ID 112 should be pre-set when accessing the create view.

Since the bookings are subscribed and the subscription returns an observable, it seems I cannot simply iterate through it and assign the last id to a variable and use this one then to determine the new ID.

The create-booking.component.ts looks as follows:

import { Component, OnInit } from '@angular/core';
import {Booking} from "../booking";
import {Router, ActivatedRoute} from "@angular/router";
import {BookingService} from "../booking.service";

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

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private bookingService: BookingService) { }

  bookings = this.bookingService.getBookings().subscribe((result) => {
    console.log(typeof result);
    return result;
  });

//TODO Make sure latest id shows up automatically


  // @ts-ignore
  booking: Booking = {
    id: 999,
    name: "Your Name",
    roomNumber: 100,
    startDate: new Date(),
    endDate: new Date(),
  }

  ngOnInit(): void {
    if(this.router.url != "/createBooking"){
      var id = Number(this.activatedRoute.snapshot.paramMap.get('id'));
      this.bookingService.getBookingById(id).subscribe((result) =>{
        this.booking = result;
      });
    }
  }

  save(): void{
    this.bookingService.addBooking(this.booking).subscribe();

    this.router.navigate(['bookings']);
  }

  dateChanged(event: Event, isStart: boolean){
    var val = (event.target as HTMLInputElement).value;

    if(isStart){
      this.booking.startDate = new Date(val);
    }
    else{
      this.booking.endDate = new Date(val);
    }
  }

}

The booking.service.ts that includes the getBookings function includes this:

import { Injectable } from '@angular/core';
import {Booking} from "./booking";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class BookingService {

  constructor(private httpClient: HttpClient) { }

  bookingsURL: string = "/api/bookings";

  getBookings(): Observable<Booking[]>{
    var resp = this.httpClient.get<Booking[]>(this.bookingsURL);
    return resp;
  }

  getBookingById(id : number) : Observable<Booking>{
    var resp = this.httpClient.get<Booking>(`${this.bookingsURL}/${id}`);
    return resp ;
  }

  delete(booking: Booking): Observable<Booking>{
    var resp = this.httpClient.delete<Booking>(`${this.bookingsURL}/${booking.id}`)
    return resp;
  }

  addBooking(booking: Booking) : Observable<Booking> {
    var resp = this.httpClient.post<Booking>(this.bookingsURL, booking);
    return resp;
  }
}

I hope you can help me to sort this out. Please bear with me in case I used an incorrect thread or did anything wring - this is my first question here :)

CodePudding user response:

You could make a very small service that does this for you.

There will only be 1 instance of this service, because you provide it in root. Therefor you can have multiple instances of your component and still end up with unique numbers. Whenever you restart your app, the number is reset. But that is something you seem to accept for now.

@Injectable({
  providedIn: 'root',
})
class NewIDService {
  private newID: number = 10001;

  public getNewIDObs(): number {     
    this.newID  = 1;
    return this.newID;
  }
}
  • Related