键入为“number”的Angular2对象属性更改为string

时间:2016-09-18 20:34:59

标签: object angular typescript typing typescript-typings

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

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

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

我已经测试过,发现它似乎不是我使用的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的实例保存到webservice:

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>

当你在name中写一些内容时双向数据绑定填充<input>属性时,问题可能已经出现但我不明白{{1}的类型可以改变吗?

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

1 个答案:

答案 0 :(得分:0)

一个小解决方案是将字段转换为with open("data.csv") as f: content = f.readlines() print(content[-3]) print(content[-3].split(",")[4:]) Out: t,h,i,s,t,h,i,s ['t', 'h', 'i', 's\r\n'] ,然后使用any将其转换为number,我今天遇到了类似的问题

有关投射的更多信息,请查看类型断言部分here