user2004
user2004

Reputation: 1973

How do I pass an URL via Angular?

This is what I am trying to do but I know that the slashes are not ok in the URL

http://localhost:57101/api/employee/holiday?userName=dinchmle&Date=05/10/2018&StateVal=2

and here is my angular service code

 updateEmployee(userName: string, holiday: Holiday): Observable<Employee> {
    return this.http.put(this._employeeUrl + '/holiday?userName=' + userName + '&Date=' + holiday.date + '&StateVal=' + holiday.state, '')
    .map((res: Employee) => res)
    .catch(this.handleError);
  }

Upvotes: 0

Views: 32

Answers (2)

Tommy
Tommy

Reputation: 2453

You could escape the slashes as %2F.

Here is the edited example:

updateEmployee(userName: string, holiday: Holiday): Observable<Employee> {
    let parsedDate = Date.parse(holiday.date);
    let month = parsedDate.getUTCMonth() + 1; //months from 1-12
    let day = parsedDate.getUTCDate();
    let year = parsedDate.getUTCFullYear();

    return this.http.put(this._employeeUrl + '/holiday?userName=' + userName + '&Date=' + day + '%2F' + month + '%2F' + year + '&StateVal=' + holiday.state, '')
        .map((res: Employee) => res)
        .catch(this.handleError);
}

Upvotes: 1

Sunil
Sunil

Reputation: 11243

Just encode your url by using encodeURI function. This will take of all special characters in your URL.

 updateEmployee(userName: string, holiday: Holiday): Observable<Employee> {
    let url = this._employeeUrl + '/holiday?userName=' + userName + '&Date=' + holiday.date + '&StateVal=' + holiday.state;

    return this.http.put(encodeURI(url), '') // encode URL
    .map((res: Employee) => res)
    .catch(this.handleError);
  }

Upvotes: 1

Related Questions