Angular http post函数如何返回布尔类型?

时间:2018-10-23 19:05:24

标签: angular post

我正在尝试调用API以返回布尔响应,但是它不起作用。 这是我的代码。

product.component.ts

obs

cart.service.ts

addToCart() {
    let item = {
      Title: this.product.name,
      UserId: parseInt(sessionStorage.getItem("id")),
      Num: parseInt(this.count.toString()),
      Img: this.product.imgs[0],
      Price: this.product.price
    }
    let existed;
    this.cartService.checkExisted(item).subscribe(res => existed = res);
    //existed is always undefined, but what expected is true or false;
    console.log("response:" + existed)  
    }
}

我使用PostMan来测试此发布请求,它可以使用正确或错误的响应正文。

1 个答案:

答案 0 :(得分:1)

checkExisted()重新调整为Observablesubscribe返回订阅。调用Subscribe是异步方法。

以下是获取所需值的正确方法。

this.cartService.checkExisted(item).subscribe(res => {
        console.log("response:" + existed) 
        existed = res;
    });


addToCart() {
    let item = {
      Title: this.product.name,
      UserId: parseInt(sessionStorage.getItem("id")),
      Num: parseInt(this.count.toString()),
      Img: this.product.imgs[0],
      Price: this.product.price
    }
    let existed;
    this.cartService.checkExisted(item).subscribe(res => {
        console.log("response:" + existed) 
        existed = res;
    });
    //existed is always undefined, but what expected is true or false;

    }
}