私は非常に単純なAngular2アプリケーションをローカルで実行しています。私は、WebサービスAPIにオブジェクトのインスタンスを送信するサービスを使用しています。 APIはスキーマに対してJSONを検証し、IDは数字でなければなりません(つまり、JSONでは引用されません)。"number"と入力した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;
}
は方法:
Webサービスへ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は数ではありません):
例の特殊文字(!!EEK Idは文字列です)WITH:
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
}
}
これは、テンプレート内の入力に結合されています:あなたは<input>
で何かを書くとき、双方向のデータバインディングname
プロパティに充填され
<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>
は多分問題が既に発生したが、私にはありませんid
のタイプがどのように変更できるのか理解していますか?プロジェクト全体のgithubのレポへ
リンク:https://github.com/djoike/ng2-cookbook/tree/master-so
興味深いバグを確認してください? updateUnitが呼び出されると、すでに文字列ですか? – worenga
あなたが言及しているラインでは、単に "unit_data"というプロパティを持つオブジェクト(objSend)を作成しているので、その行の前には存在しません。 – MOV
しかし、 'unit'(引数)はどこか正しいところから来ますか? ... – worenga