#angular #angular-material #angular9
#angular #angular-материал #angular9
Вопрос:
Я не могу получить данные журнала консоли после отправки формы.. Чего мне не хватает в моем приведенном ниже коде.. Этот код долго сожалеет об этом..
HTML:
<form [formGroup]="collFormEvening" autocomplete="off" (submit)="onSubmit()">
<label class="label">Evening [Machine 1]</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Cash <small
class="mandatory">*</small></span>
</div>
<input type="number" formControlName="Cash" class="form-control" required>
<input type="number" formControlName="Cash2" class="form-control" readonly>
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Card</span>
</div>
<input type="number" formControlName="Card" class="form-control" >
<input type="" formControlName="Card2" class="form-control" id="dcard"
readonly>
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Phone Pay</span>
</div>
<input type="number" formControlName="PhonePay" class="form-control"
id="phonePay">
<input type="" formControlName="PhonePay2" class="form-control"
id="dphonePay" readonly>
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Ecommerce</span>
</div>
<input type="number" formControlName="Ecom" class="form-control" >
<input type="" formControlName="Ecom2" class="form-control"
readonly>
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Others</span>
</div>
<input type="number" formControlName="Other" class="form-control" >
<input type="" formControlName="Other2" class="form-control"
readonly>
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >1000X</span>
</div>
<input type="number" formControlName="Thousand"
class="form-control">
<input type="number" formControlName="Thousand2"
class="form-control" readonly>
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >500X</span>
</div>
<input type="number" formControlName="FiveHundred"
class="form-control">
<input type="number" formControlName="FiveHundred2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >100X</span>
</div>
<input type="number" formControlName="Hundred"
class="form-control">
<input type="number" formControlName="Hundred2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >50X</span>
</div>
<input type="number" formControlName="Fifty" class="form-control">
<input type="number" formControlName="Fifty2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >20X</span>
</div>
<input type="number" formControlName="Twenty"
class="form-control">
<input type="number" formControlName="Twenty2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >10X</span>
</div>
<input type="number" formControlName="Ten" class="form-control">
<input type="number" formControlName="Ten2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >5X</span>
</div>
<input type="number" formControlName="Five" class="form-control">
<input type="number" formControlName="Five2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >2X</span>
</div>
<input type="number" formControlName="Two" class="form-control">
<input type="number" formControlName="Two2" readonly
class="form-control">
</div><br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" >1X</span>
</div>
<input type="number" formControlName="One" class="form-control">
<input type="number" formControlName="One2" readonly
class="form-control">
</div><br>
<div class="input-group">
<input type="text" value="Total" class="form-control" readonly>
<input type="number" formControlName="Total2"
class="form-control text-center" readonly>
</div><br>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4"><br>
<div type="submit" class="btn btn-primary mt-1"><i class="fas fa-save mr-2">
</i>Submit</div>
<button type="reset" value="reset"
class="btn btn-light mt-2">Clear</button>
</div>
<div class="col-md-4"></div>
</div>
</form>
ts: это файл ts, и после отправки формы я не могу получить данные консоли. Есть ли какая-либо ошибка, которую я совершил ??
ngOnInit(): void {
this.onKeyUpMethod();
this.onKeyUpMethodEvening();
}
onSubmit() {
console.log(this.collFormMorning.value); <--! here is the code to get form data in console -->
this.collectionService.postItems(this.collFormMorning.value).subscribe(
(res: any) => {
this.toastr.success("Sales collection saved successfully !!");
console.log(res);
console.log(this.collFormMorning.value); <--! here is the code to get form data in console -->
this.collFormMorning.reset();
},
err => {
if (err.status == 400)
this.toastr.error('Error !!', 'Authentication failed.');
else
this.toastr.error('Network error', 'Authentication failed.');
console.log(err);
}
);
}
onKeyUpMethod() {
this.collFormMorning = this.fb.group({
Cash: [''],
Cash2: [''],
Card: [''],
Card2: [''],
PhonePay: [''],
PhonePay2: [''],
Ecom: [''],
Ecom2: [''],
Other: [''],
Other2: [''],
Thousand: [''],
Thousand2: [''],
FiveHundred: [''],
FiveHundred2: [''],
Hundred: [''],
Hundred2: [''],
Fifty: [''],
Fifty2: [''],
Twenty: [''],
Twenty2: [''],
Ten: [''],
Ten2: [''],
Five: [''],
Five2: [''],
Two: [''],
Two2: [''],
One: [''],
One2: [''],
Total: [''],
Total2: [0],
});
this.collFormMorning.get('Cash').valueChanges
.subscribe(a => {
this.collFormMorning.get('Cash2').setValue(a);
this.setTotalValue();
})
this.collFormMorning.get('Card').valueChanges
.subscribe(x => {
this.collFormMorning.get('Card2').setValue(x);
this.setTotalValue();
})
this.collFormMorning.get('PhonePay').valueChanges
.subscribe(a => {
this.collFormMorning.get('PhonePay2').setValue(a);
this.setTotalValue();
})
this.collFormMorning.get('Ecom').valueChanges
.subscribe(x => {
this.collFormMorning.get('Ecom2').setValue(x);
this.setTotalValue();
})
this.collFormMorning.get('Other').valueChanges
.subscribe(x => {
this.collFormMorning.get('Other2').setValue(x);
this.setTotalValue();
})
this.collFormMorning.get('Thousand').valueChanges
.subscribe(a => {
this.collFormMorning.get('Thousand2').setValue(a * 1000);
this.setTotalValue();
})
this.collFormMorning.get('FiveHundred').valueChanges
.subscribe(a => {
this.collFormMorning.get('FiveHundred2').setValue(a * 500);
this.setTotalValue();
})
this.collFormMorning.get('Hundred').valueChanges
.subscribe(x => {
this.collFormMorning.get('Hundred2').setValue(x * 100);
this.setTotalValue();
})
this.collFormMorning.get('Fifty').valueChanges
.subscribe(a => {
this.collFormMorning.get('Fifty2').setValue(a * 50);
this.setTotalValue();
})
this.collFormMorning.get('Twenty').valueChanges
.subscribe(x => {
this.collFormMorning.get('Twenty2').setValue(x * 20);
this.setTotalValue();
})
this.collFormMorning.get('Ten').valueChanges
.subscribe(a => {
this.collFormMorning.get('Ten2').setValue(a * 10);
this.setTotalValue();
})
this.collFormMorning.get('Five').valueChanges
.subscribe(x => {
this.collFormMorning.get('Five2').setValue(x * 5);
this.setTotalValue();
})
this.collFormMorning.get('Two').valueChanges
.subscribe(a => {
this.collFormMorning.get('Two2').setValue(a * 2);
this.setTotalValue();
})
this.collFormMorning.get('One').valueChanges
.subscribe(x => {
this.collFormMorning.get('One2').setValue(x * 1);
this.setTotalValue();
})
}
setTotalValue() {
const data = this.collFormMorning.value;
let sum = 0;
Object.keys(data).map(key => {
if (['Cash2', 'Card2', 'PhonePay2', 'Ecom2', 'Other2', 'Thousand2', 'FiveHundred2', 'Hundred2',
'Fifty2', 'Twenty2', 'Ten2', 'Five2', 'Two2', 'One2'].indexOf(key) !== -1 amp;amp; data[key]) {
sum = data[key];
//console.log(sum);
}
});
this.collFormMorning.get('Total2').setValue(sum);
};
Есть ли что-то недостающее в этом коде .. пожалуйста, помогите мне решить эту проблему , я новичок в angular
Когда я отправляю данные формы, я получаю эту ошибку.. когда я меняю type=»number» на text, он работает нормально. Изображение ошибки .. пожалуйста, взгляните.
Контроллер:
// POST: api/CollectionEntry
// To protect from overposting attacks, enable the specific properties
you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<SalesCollectionEntry>>
PostSalesCollectionEntry(SalesCollectionEntry salesCollectionEntry)
{
_context.SalesEntry.Add(salesCollectionEntry);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSalesCollectionEntry", new { id =
salesCollectionEntry.Id }, salesCollectionEntry);
}
Класс:
public class SalesCollectionEntry
{
[Key]
public int Id { get; set; }
public string Division { get; set; }
public string Name { get; set; }
public string Terninal { get; set; }
public string Shift { get; set; }
[DataType(DataType.Date)]
public DateTime PostDateTime { get; set; }
public decimal Cash { get; set; }
public decimal Cash2 { get; set; }
.
.
. //etc
}
Обновленный код,
класс обслуживания:
export class CollectionService {
//collectionInfo : Collection[]= [];
constructor(private http: HttpClient) { }
readonly BaseURL = 'https://localhost:44372/api';
// save data of Items to db
postItems(data){
return this.http.post(this.BaseURL "/CollectionEntry", data);
}
}
Комментарии:
1. Возможно, вы уже видите сброшенные значения формы. Если вы можете, добавьте, пожалуйста, ссылку на StackBlitz.
2. Теперь он работает нормально после изменения тега div на button.. Я только что допустил ошибку здесь.. Спасибо, В.Тур, ты всегда рядом со мной, чтобы помочь .. много любви .. 🙂
3. V.Tur я получаю сообщение об ошибке при отправке данных формы на сервер.. я прикрепил SS pic выше.. пожалуйста, взгляните.. У вас есть какие-либо идеи по этому поводу.. Я застрял здесь..
4. Для ответа недостаточно информации: (Нужно посмотреть, какой JSON вы отправляете, и я не силен в C #, но, может быть, на серверной части вам нужно получить поток, а затем сериализовать его?
5. я отправляю данные формы (т.Е. Номер), которые являются формой номинала .. вы выполнили форму номинала (код вычисления). Когда я отправляю другую форму, она работает нормально.
Ответ №1:
<form [formGroup]="collFormEvening" autocomplete="off" (submit)="onSubmit()">
на этой HTML-странице, я думаю, [FormGroup] не равен параметру console.log
console.log(this.collFormMorning.value);