I can't seem to access the response to my login request after upgrading from Angular's Http
to HttpClient
. This is the working code for Http:
login(username: string, password: string): Observable<boolean> {
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this.http.post('http://localhost:8080/oauth/login', '', {headers: headers, withCredentials: true})
.map((response: Response) => {
if (response.status === 200) {
localStorage.setItem('setCookie', resHeaders.get("Set-Header"));
window.location.href = "http://localhost:8080/oauth/authorize?client_id=api&response_type=token&redirect_uri=http://" + document.location.host + "/%23/token//%3F";
return true;
}
else {
return false;
}
});
}
This is the code I use for HttpClient:
login(username: string, password: string): Observable<boolean> {
let httpHeaders : HttpHeaders = new HttpHeaders()
.set("Authorization", "Basic " + btoa(username + ":" + password))
.set("Content-Type", "application/x-www-form-urlencoded");
return this.http.post('http://localhost:8080/oauth/login', '', {headers: httpHeaders, withCredentials: true})
.pipe(
map(res => { // res: undefined
if (res) {
console.log("res: " + res);
}
else {
console.log("Didn't get any response");
}
})
)
}
Output from the HttpClient
code is Didn't get any response
. HttpClient Docs uses pipe like in my code above, but res
is also undefined if I just use .map
like I do with Http
. I have examined the actual requests and responses in Chrome, and they are identical to the working code using Http
. So I know that the problem is that I'm doing something wrong when trying to access the response object.
It seems like all that was missing is that I needed to add observe: 'response'
to the request options, like so:
login(username: string, password: string): Observable<boolean> {
let httpHeaders : HttpHeaders = new HttpHeaders()
.set("Authorization", "Basic " + btoa(username + ":" + password))
.set("Content-Type", "application/x-www-form-urlencoded");
return this.http.post('http://localhost:8080/oauth/login', '', {headers: httpHeaders, withCredentials: true, observe: 'response'})
.pipe(
map(res => { // res: [object Object]
if (res) {
console.log("res: " + res);
}
else {
console.log("Didn't get any response");
}
})
)
}
This allows me to access the response headers that I need, as per the docs.