Nicolas
Nicolas

Reputation: 4756

Angular 2 - GET Request with optional headers

I want to do a GET request, with multiple parameters, however only 1 is required.

Currently I have this code to do my request (I want to do a call without any of the optional parameters):

Service:

public getAbsenceReservations(From: Date, ReservationStateID?: number, Resource?: string, To?: Date): Observable<models.AbsenceReservation> {

    let params: URLSearchParams = new URLSearchParams();
    params.set("From", From.toString());
    params.set("ReservationStateID", ReservationStateID.toString());
    params.set("Resource", Resource);
    params.set("To", To.toString());

    const path = `${this.apiEndpoint}Time/Absence`;
    return this.http.get(path, { search: params })
        .map((response: Response) => new models.AbsenceReservation().deserialize(response.json().Data))
        .catch(this.handleError);
}

Component:

private getAbsenceReservations() {
    this.loaderService.setEnableLoader(true);
    this.AbsenceService.getAbsenceReservations(this.fromDate, this.reservationStateID, this.resource, this.toDate)
        .subscribe(
        response => {
            this.absenceReservations = response;
            this.absenceReservationsChange.emit(this.absenceReservations);
            this.loaderService.setEnableLoader(false);
        },
        error => console.log("error")
        );
}

I receive the error

Cannot read property 'toString' of undefined

Ofcourse none of the optional parameters are defined, which is what's causing the error.

What's the correct way to code a GET request with optional parameters?

Example

If I have 0 optional defined optional variables

api.com/?from=timestamp

But if I have 1 or more do this

api.com/?from=timestamp&Resource=RandomString

Upvotes: 1

Views: 1080

Answers (1)

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11596

You just need to put if check as follows. Everything else are perfect.

params.set("From", From.toString()); //Required
if(ReservationStateID) params.set("ReservationStateID", ReservationStateID.toString());
if(Resource) params.set("Resource", Resource);
if(To) params.set("To", To.toString());

Upvotes: 2

Related Questions