Angular发送http请求获取结果判断失败

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']);
      }
      //修改的地方
    })
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值