Angular 2 - 带有可选标头的GET请求

时间:2017-03-27 10:26:21

标签: angular get request-headers

我想使用多个参数执行GET请求,但只需要1个。

目前我有这个代码来执行我的请求(我想在没有任何可选参数的情况下进行调用)

服务

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);
}

组件:

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")
        );
}

我收到错误

Cannot read property 'toString' of undefined

当然没有定义任何可选参数,这是导致错误的原因。

使用可选参数编​​写GET请求的正确方法是什么?

示例

如果我有0个可选的已定义可选变量

api.com/?from=timestamp

但如果我有1个或更多人这样做

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

1 个答案:

答案 0 :(得分:2)

你只需要检查如下。其他一切都很完美。

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());