首页 > 解决方案 > 在 Angular / HTTP POST 请求中作为空白传递的布尔数据

问题描述

我正在尝试将一些数据发布到 API,而我的布尔数据一直显示为空白。有没有人对可能导致这种情况的原因有任何想法?

const notifications: Array<Notification> = [
    {
        id: "all",
        title: "All",
        isActive: false
    }
 ];

这是我interface的数据:

export interface Notification {
    id: string,
    title: string,
    isActive: boolean
}

现在,当我尝试通过HTTP POST请求传递这些数据时,它显示为:

notifications: [
    {
        "id": "all",
        "title": "All",
        "isActive": ""
    }
 ];

我注意到isActive当我通过 Safari/Chrome 检查调用时该属性为空白http.post(),这导致我的 API 出现问题,因为数据看起来是空白而不是布尔值。

这是我将数据传递给 API 的方式:

this.http.post('/api/', {notifications: notifications}).subscribe((res:any) => {
    console.log(res);
}

标签: angularhttp-post

解决方案


尝试这个。在发送转换布尔值 toString 之前isActive.toString()

所以在制作api之前你可以做

notifications = {...notifications, isActive: notifications.isActive.toString() };

推荐阅读