我正在尝试发送密码到我的服务器->服务器检查它是否正确密码->发送状态码:200Success或401Error。
现在我正在检查状态代码,但我觉得应该有更好的方法,因为我的代码看起来很笨拙。
我基本上只想检查这两个状态代码。
getTokenFromServer(value: Authentication): Observable <Authentication>{
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
return this.http.post(serverUrl, value, httpOptions).pipe(
tap((response: any) => {
if(response.status == "200"){
console.log("Success logging in: "+response.status+":"+response.token);
this.tokenService.setToken(response.token);
}else{
console.log("Error logging in: " +response.status);
}
}),
catchError(this.handleError('Authenticate password:'))
);
}发布于 2018-06-22 06:21:15
只有2xx状态码会进入你的点击功能,所以if检查是不必要的。401状态码将导致抛出一个错误,这将由catchError函数引起。您可以简化为:
return this.http.post(serverUrl, value, httpOptions).pipe(
tap((response: any) => {
console.log("Success logging in: "+response.status+":"+response.token);
this.tokenService.setToken(response.token);
}),
catchError(this.handleError('Authenticate password:'))
);https://stackoverflow.com/questions/47351418
复制相似问题