Angular http post函数如何返回布尔类型?
我试图调用一个API来返回布尔响应,但它不起作用。 这是我的代码 product.component.tsAngular http post函数如何返回布尔类型?,angular,post,Angular,Post,我试图调用一个API来返回布尔响应,但它不起作用。 这是我的代码 product.component.ts addToCart() { let item = { Title: this.product.name, UserId: parseInt(sessionStorage.getItem("id")), Num: parseInt(this.count.toString()), Img: this.product.imgs[0],
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)
}
}
cart.service.ts
@Injectable()
export class CartService {
constructor(private http: Http) { }
checkExisted(item) {
return this.http.post("/api/Cart/CheckCartItem", item).map(res =>
res.text());
}
}
我用PostMan测试了这个post请求,它可以处理正确或错误的响应体。checkExisted()retunedObservable
和subscribe
返回订阅。调用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;
}
}
您不能认为异步函数以同步方式工作,
existed
值只有在调用subscribe
函数后才可用。所以考虑把控制台放在代码>订阅/代码>功能中,这是标准错误,人们犯了与<代码>异步> /代码>调用…当您订阅某些内容时,它不会立即执行(它是异步的),因此您需要控制台。将它记录在subscribe块中。但是如果我需要现有的值来处理下一个代码逻辑,该怎么办?例如,如果存在为真,则做某事,否则做某事。然后将结果放入块中,并在该块中做某事。。。如果您不知道如何在subscribe方法中创建块,请检查下面的答案…非常感谢同志们,它很有效。也许我需要更多的时间来计算角度上的可观测值!非常感谢。但如果我们将“console.log”(“response:+existed”)放在“existed=res”之前。结果是否仍然未定义?@HanwenGuo existed此时将未定义,因为该值未分配给existed