【问题标题】:Angular2 object property typed as "number" changes to string类型为“数字”的 Angular2 对象属性更改为字符串
【发布时间】:2016-09-18 20:34:58
【问题描述】:

我有一个非常简单的 Angular2 应用程序在本地运行。我正在使用服务将对象的实例发送到 Web 服务 API。 API 根据模式验证 JSON,ID 必须是数字(即不在 JSON 中引用)。

我的问题是,当我尝试将对象发送到网络服务时,我的 ID 字段周围有引号,即使它在 Typescript 中输入为数字。

仅当对象的nameproperty 包含“特殊字符”时才会观察到该行为。

我已经测试并发现它似乎不是我使用的 JSON.stringify - 请参阅下面的代码。

应用程序是用 Typescript 编写的。

单元类:

export class Unit {
    id: number;   // This is the problem child
    name: string; // This is the string that can contain special characters
    short: string;
    triggers_plural: number;
    is_headline: boolean;
}

保存方法:
我将Unit 的实例保存到网络服务的代码:

updateUnit(unit: Unit): Promise<Unit>
{
    var objSend = {unit_data: [unit]};          // Webservice expects an array of units

    console.log(objSend.unit_data[0].id === 2); // Yields false when ID is 2
    console.log(objToReturn);                   // Logs ID to verify it is 2 when testing

    // Code for actual request
    return this.http.put(`${this.unitUrl}/${unit.id}`, JSON.stringify(objSend),{headers:this.headers})
    .toPromise()
    .then(()=> unit)
    .catch(this.handleError);
}

运行代码并调用方法时,当Unit对象的name属性包含特殊字符时,控制台将记录ID不相等。

没有特殊字符的例子(没问题,id是数字):

带有特殊字符的示例(eek!Id 是一个字符串!):

updateUnit 方法是从我的单元详细信息组件中调用的,您可以在其中编辑单元:

export class UnitDetailComponent implements OnInit {
    unit: Unit; // this.unit later on

    constructor(
        private unitService: UnitService,
        private route: ActivatedRoute
    ){}

    ngOnInit(): void
    {
        this.route.params.forEach((params: Params) => {
            let id = +params['id']; // The routing will give id to look for
            this.unitService.getUnit(id)
            .then(unit => this.unit = unit); // Here the unit is instanciated in the first place
        });
    }

    save(): void
    {
        this.unitService.updateUnit(this.unit).then(this.goBack); // Here is the call to updateUnit method
    }
}

它绑定到模板中的输入:

<div *ngIf="unit">
    <div>
        <label>Edit unit</label>
        <div>
          <input type="text" [(ngModel)]="unit.name" />
        </div>
    </div>
    <button class="btn btn-default" type="button" (click)="save()">Save</button>
</div>

当你在&lt;input&gt;中写一些东西时,当双向数据绑定填充name属性时,问题可能已经出现但我不明白id的类型如何改变?

整个项目的github repos链接:https://github.com/djoike/ng2-cookbook/tree/master-so

【问题讨论】:

  • 有趣的Bug,unit_data从哪里来?调用 updateUnit 时是否已经是字符串?
  • 在你提到的那一行,我只是创建了一个带有属性“unit_data”的对象(objSend),所以它在该行之前的任何地方都不存在。
  • unit(论点)来自某个地方,对吗? ...
  • 是的,上面一行的函数中传入了:updateUnit(unit: Unit)
  • 好的,但这意味着错误是单元对象最初实际创建的位置,而不是您提供给我们的函数,那么 updateUnit 调用在哪里?

标签: object angular typescript typing typescript-typings


【解决方案1】:

一个小解决方案是将字段转换为 any ,然后使用 parseInt() 将其转换为 number ,我今天遇到了类似的问题

有关强制转换的更多信息,请查看 类型断言 部分 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2013-06-15
    • 2022-01-09
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多