我正在開發使用導軌後端的角應用程序。我有問題格式化參數散列,所以軌道可以使用它。數據是多對多的關係,表單包含嵌套的屬性。在Rails中,我的模型使用了幫助器accepts_nested_attributes_for
。我知道到底是什麼格式的軌道期望,但是當我做一個POST
要求,有一個小細節這關。我將在下面列出兩個參數哈希值。一個是Angular產生的,另一個是Rails期望的。角4&導軌5 POST請求JSON格式
什麼是關閉對角請求軌道預計在expense_expense_categories
屬性嵌套的更深了一層。我從來沒有明白爲什麼軌道需要它。什麼角度產生看起來合乎邏輯的我。我的問題是..我需要做什麼來格式化Angular中的參數?看看我到目前爲止,我是否以滿足角度最佳實踐的方式來完成此任務?
角:
{
"expense": {
"date": "2017/4/13",
"check_number": "132",
"debit": "0",
"notes": "har",
"amount": "24",
"payee_id": "334"
},
"expense_expense_categories_attributes": [{
"expense_category_id": "59",
"amount": 12
},
{
"expense_category_id": "62",
"amount": 11
}
]
}
什麼Rails的預計:
{
"expense": {
"date": "2017/12/12",
"check_number": "122",
"debit": "0",
"notes": "har",
"amount": "24",
"payee_id": "334",
"expense_expense_categories_attributes": {
"210212312": {
"expense_category_id": "72",
"amount": "12"
},
"432323432": {
"expense_category_id": "73",
"amount": "12"
}
}
}
}
我的角度代碼如下。
onSubmit()
方法成分:
onSubmit() {
this.expenseService.addExpense(this.expenseForm.value)
.subscribe(
() => {
this.errorMessage = '';
},
error => {
this.errorMessage = <any>error;
}
);
this.expenseForm.reset();
}
addExpense在我的服務文件:
addExpense(expense: Expense): Observable<any> {
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post('http://localhost:3000/expenses', expense, options)
.map(
(res: Response) => {
const expenseNew: Expense = res.json();
this.expenses.push(expenseNew);
this.expensesChanged.next(this.expenses.slice());
})
.catch(this.handleError);
}
我的主要形式有:
private initForm() {
let expense_expense_categories_attributes = new FormArray([]);
this.expenseForm = this.fb.group({
id: '',
date: '',
amount: '',
check_number: '',
debit: '',
payee_id: '',
notes: '',
expense_expense_categories_attributes: expense_expense_categories_attributes
});
}
我FormArray嵌套屬性:
onAddExpenseCategories() {
(<FormArray>this.expenseForm.get('expense_expense_categories_attributes')).push(
new FormGroup({
'expense_category_id': new FormControl(null, Validators.required),
'amount': new FormControl(null, [
Validators.required
])
})
);
}
更新:我能得到它的工作,但我不得不用神可怕的正則表達式來處理請求我想要的東西。這是一個非常醜陋的選擇,所以我仍然需要找到一個更好的選擇。有沒有更好的方式來格式化JSON對象並替換內容?我不確定正確的做法。需要幫忙。
您是否嘗試過使用'wrap_parameters'爲':json'? http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html – Jon
@喬恩這似乎是默認使用Rails在API模式下啓用 – ctilley79
是的,但默認情況下它只會包住模型本身的屬性。如果您傳遞其他屬性,例如'expense_categories_attributes',那麼您將需要明確地將這些屬性添加到包裹的參數中。 – Jon