从Angular的Http
升级到HttpClient
后,我似乎无法访问对我的登录请求的回复。这是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;
}
});
}
这是我用于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");
}
})
)
}
HttpClient
代码的输出为Didn't get any response
。 HttpClient Docs在上面的代码中使用了管道,但如果我像使用res
一样使用.map
,Http
也是未定义的。我检查了Chrome中的实际请求和响应,它们与使用Http
的工作代码相同。所以我知道问题在于我在尝试访问响应对象时做错了什么。
答案 0 :(得分:1)
您必须立即使用subscribe函数来访问您的Responseobject。
请注意,您现在将返回订阅对象。 尝试这样的事情:
return this.http.post('http://localhost:8080/oauth/login', '', {headers: httpHeaders, withCredentials: true})
.subscribe(res => {
console.log("res: " + res);
},
error => {
console.log("error" + error);
}
);
答案 1 :(得分:0)
似乎缺少的是我需要在请求选项中添加observe: 'response'
,如下所示:
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");
}
})
)
}
根据docs。
,这允许我访问我需要的响应标头