Angular发送http请求获取结果判断失败
问题描述
做注册功能的时候,想要获取返回数据的状态码进行判断,结果一直判断为false。
原因分析
自定义结果集
public class MyResult {
private String msg;
private int code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public MyResult() {
}
public MyResult(String msg, int code) {
this.msg = msg;
this.code = code;
}
}
返回结果
@PostMapping("/register")
public MyResult register(@RequestBody LoginUser user){
Integer flag = 1;
if (flag != 0){
return new MyResult("Register success", 200);
}
return new MyResult("Register fail", 201);
}
Angular代码
register(): void{
this.personInfo.username = this.peopleInfo.username;
this.personInfo.password = this.peopleInfo.password;
const httpOptions = {headers: new HttpHeaders({ 'Content-Type': 'application/json', "Authorization":"register"})};
let api = 'http://localhost:8001/admin/register';
this.http.post(api, JSON.stringify(this.personInfo), httpOptions).subscribe((response)=>{
console.log(this.result+" " + response)
this.result = response;
})
console.log("111"+this.result)
if(this.result.code == "200"){
this.router.navigate(['/login']);
}
}
调试之后的输出结果
在这里才突然想起Angular的http是异步请求,我不小心将判断语句放错了位置。也就是说,在我访问后端的时候,结果还没返回来,我就已经进行判断了,那么结果自然就是false。
解决方案
将判断的业务逻辑放到请求的回调函数中
register(): void{
this.personInfo.username = this.peopleInfo.username;
this.personInfo.password = this.peopleInfo.password;
const httpOptions = {headers: new HttpHeaders({ 'Content-Type': 'application/json', "Authorization":"register"})};
let api = 'http://localhost:8001/admin/register';
this.http.post(api, JSON.stringify(this.personInfo), httpOptions).subscribe((response)=>{
this.result = response;
//修改的地方
if(this.result.code == "200"){
this.router.navigate(['/login']);
}
//修改的地方
})
}