2016-09-18 84 views
0

我有一個非常簡單的Angular2應用程序在本地運行。我正在使用服務將對象的實例發送給webservice API。 API針對模式驗證JSON,並且ID必須是數字(即不在JSON中引用)。鍵入爲「數字」的Angular2對象屬性更改爲字符串

我的問題是,當我嘗試發送對象到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); 
} 

當運行代碼,並調用方法,控制檯會記錄該ID不等於Unit對象的name屬性包含特殊字符。

無特殊字符示例(沒問題,身份證是一個數字):

包含特殊字符的實例(伊克編號是一個字符串!):

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>的東西,但我不瞭解如何改變id的類型?

鏈接到整個項目的github上回購:https://github.com/djoike/ng2-cookbook/tree/master-so

+0

有趣的Bug,unit_data從哪裏來?當updateUnit被調用時它已經是一個字符串了嗎? – worenga

+0

在你提到的這一行上,我只是簡單地創建了一個帶有屬性「unit_data」的對象(objSend),所以它不存在於該行之前的任何地方。 – MOV

+0

但是'unit'(參數)來自某個地方? ... – worenga

回答

0

小解決方案是到外地轉換爲any,然後將其轉換爲使用parseInt()一個number來,我今天遇到了類似的問題

有關鑄造的更多信息,請檢查類型斷言部分here

相關問題