Search code examples
angularangular-servicesangular2-observables

angular httpClient get orders with or without a filter by date


I have specification date that says get orders where date = date1 >= :date and date2=< :date and if both dates are null it should return all orders basically basically both urls should pass from one service baseUrl : string = 'http://localhost:8088/orders'; private filterUrl: string = 'http://localhost:8088/orders?start= &end= ';

How can i achieve this in angular service and how do i call it in my component i started like this but im new to angular dont know how to go by the logic

  getOrders(From: Date, To: Date): Observable<Order[]> {
return this.http.get(this.baseUrl + '?start=' + From + '&end=' +To)
  .pipe(map(this.extractData),
    tap(data => console.log(JSON.stringify(data))),
    catchError(this.handleError)
  );

} what i want is for my html to show the whole list automatically and should filter if both dates are passed,my thoughts are i will not in this case need the baseUrl above i will use the filter url and defaults should be null can someone show me how to continue thank you. here is my sql incase

SELECT orderId, petrolQty, orderDate, truckId from orderz \
where (orderDate>=:start or :start is null) and (orderDate<=:end or :end is null)

so basically i will be filtering by orderDate So what i did now is this

 baseUrl : string = 'http://localhost:8088/orders';

  getOrders(From: Date, To: Date): Observable<Order[]> {
    return this.http.get(this.baseUrl + '?start=' + From + '&end='+To)
      .pipe(map(this.extractData),
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

and in my component i did this

  start: Date = null;
  end: Date = null;

  constructor(private orderService: OrderService, private router: Router) {
  }

  ngOnInit() {
    this.orders = this.getOrdersDto();
  }


  private getOrdersDto() {

    return this.orderService.getOrders(this.start, this.end)
  }

the url i set to null and tried on postman it gave exception unparcable date null, this is because i set them to null ,now the issue is can i create and if service get method ,that will use 'http://localhost:8088/orders when dates are set to null and when i put dates it will it will use the new dates to filter


Solution

  • Instead of constructing your URL dynamically, let Angular do that for you.

    import { HttpClient, HttpParams } from '@angular/common/http';
    
    baseUrl : string = 'http://localhost:8088/orders';
    
    getOrders(from: Date, to: Date): Observable<Order[]> {
        const params = new HttpParams();
    
        if (from) {
            params.set('start', from);
        }
    
        if (to) {
            params.set('end', to);
        }
    
        return this.http.get(this.baseUrl, { params: params })
            ...;
    }