Удаление выбранной строки (ngx-datatable), сообщение об ошибке HTTP-ответа - PullRequest
0 голосов
/ 25 мая 2020

Когда я пытаюсь удалить выбранную строку, я получаю следующее сообщение об ошибке: "" Ответ об ошибке HTTP для https://localhost: 44354 / api / cards / delete : 400 OK "" также я добавил в скриншот.

Кто-нибудь может помочь мне найти, что не так.

Angular8, Asp. Net Core 2.1

component.ts

import { Component, OnInit, ViewChild }               from '@angular/core';
import { trigger, transition, style, animate }        from '@angular/animations';
import { FormGroup, FormBuilder, Validators }         from '@angular/forms';
import { DatatableComponent }                         from '@swimlane/ngx-datatable/';

import { CardModel }                                  from '../../../models/card-models/card-model';
import { CardService }                                from '../../../services/card-services/card.service';
import { HttpClient }                                 from '@angular/common/http';


@Component({
  selector: 'app-card-page',
  templateUrl: './card-page.component.html',
  styleUrls: ['./card-page.component.scss'],
  providers: [CardService],
  animations: [
    trigger('fadeInOutTranslate', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('400ms ease-in-out', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        style({ transform: 'translate(0)' }),
        animate('400ms ease-in-out', style({ opacity: 0 }))
      ])
    ])
  ]
})
export class CardPageComponent implements OnInit {

  constructor(
    private cardService:CardService,
    private formBuilder:FormBuilder,
    private httpclient:HttpClient
  ) { }

  cards:CardModel[];
  card:CardModel;
  deletedCard: any;
  cardAddForm: FormGroup;

  rows = [];
  temp = [];
  deleted = {};
  selected = [];
  checkbox = [];
  columns: any[] = [
    { name: "Id" },
    { name: 'No' },
  ];

  ngOnInit() {
    this.createCardForm();
    this.getCardsList();
  }

  @ViewChild(DatatableComponent, {static:true}) table: DatatableComponent;

  createCardForm() {
    this.cardAddForm = this.formBuilder.group({
      no: ["", Validators.required],
    })
  }

  getCardsList(){
    this.cardService.getCardsList().subscribe(data=>{
      this.cards = data;
      this.temp = data;
    })
  }

  add() {
    if (this.cardAddForm.valid) 
    {
      this.card = Object.assign({}, this.cardAddForm.value)
      console.log(this.card)
      this.cardService.add(this.card)
    }
    //Bu alana No kontrolü yaptırmalıyız. Eğer eklenmeye çalışan no varsa, tekrar eklenmemeli, yada backend servise yazmalıyız.
  }

  delete(){
    console.log(this.card)
    this.cardService.delete(this.card)
  }

  onSelect({selected}) {
    console.log('Select Event', selected, this.selected);
  }

  onActivate(event) {
    {
      if(event.type == 'click') {
        console.log(event.row);
        this.card = event.row
      }
    }
  }

  updateFilter(event) {
    const val = event.target.value.toLowerCase();
    // filter our data
    const temp = this.temp.filter(function (d) {
      return d.no.toLowerCase().indexOf(val) !== -1 || !val;
    });
    // update the rows
    this.cards = temp;
    // Whenever the filter changes, always go back to the first page
    // this.table.offset = 0;
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { AlertifyService } from '../_common-services/alertify-service/alertify.service';
import { CardModel } from '../../models/card-models/card-model'
import { Observable } from 'rxjs';
import { EnvironmentsDefination } from '../../../environments/environments-defination';
import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';
import { ToastService } from '../_common-services/toast-service/toast.service';
import { data } from 'jquery';


@Injectable({
  providedIn: 'root'
})
export class CardService {

  constructor(
    private httpClient: HttpClient,
    private alertifyServie: AlertifyService,
  ) { }

  path = EnvironmentsDefination.path

  getCardsList(): Observable<CardModel[]> {
    return this.httpClient.get<CardModel[]>(this.path + 'cards');
  }

  add(card) {
    return this.httpClient.post(this.path + 'cards/add', card).subscribe(data => {
      this.alertifyServie.success("Card is added")
    })
  }

  update() {

  }

  delete(card: CardModel) {
    let headers = new HttpHeaders();
    headers = headers.append("Content-Type", "application/json")
    return this.httpClient
    .delete(this.path + 'cards/delete', card, { headers: headers, responseType:"text"})
    .subscribe(data => {
      this.alertifyServie.success("Card is deleted")
    })
  }

}

html

<div class="row">
  <div class="col-lg-12">
    <app-card [title]="'Card Defination & List Page'"
      [headerContent]="'From this Application Card, You can click tabs to reach functions'" [blockClass]="'tab-icon'">
      <div class="row">
        <div class="col-lg-12">
          <!-- <div class="sub-title">Tab With Icon</div> -->
          <div class="md-tabs">
            <ngb-tabset>
              <ngb-tab>
                <!-- Iconlar İşe uygun seçilecek. -->
                <ng-template ngbTabTitle><i class="icofont icofont-home"></i>Card Creation</ng-template>
                <ng-template ngbTabContent>
                  <div [@fadeInOutTranslate] class="m-t-15">
                    <form _ngcontent-yaj-c31="" novalidate="" class="ng-untouched ng-pristine ng-valid"
                      [formGroup]="cardAddForm" (ngSubmit)="add()">
                      <div class="form-group-row">
                        <!-- TODO Style global css'e eklenecek ve oradan çekilecek. -->
                        <div class="form-row" style="float: right;">
                          <div class="btn-group btn-group-sm btn-group" style="margin-right: 5px; margin-top: 5px;">
                            <button [disabled]="!cardAddForm.valid" type="submit" id="save" class="btn btn-primary"
                              style="margin-right: 3px; width: 75px;">Add</button>
                          </div>
                        </div><br><br>
                        <div class="form-row">
                          <label class="col-sm-2 col-form-label">No: </label>
                          <input class="col-sm-3 form-control" mask="0000-0000-0000-0000" type="text" id="no"
                            formControlName="no" placeholder="####-####-####-####" required>
                          <span class="form-control-warning" style="margin-left: 5px;"
                            *ngIf="cardAddForm.get('no').hasError('required') && cardAddForm.get('no').touched">
                            Please write Card No.
                          </span>
                        </div><br>
                      </div>
                    </form>
                  </div>
                </ng-template>
              </ngb-tab>
              <ngb-tab>
                <ng-template ngbTabTitle><i class="icofont icofont-home"></i>List of Cards</ng-template>
                <ng-template ngbTabContent>
                  <div [@fadeInOutTranslate] class="m-t-15">
                    <div class="dt-responsive">
                      <div class="row">
                        <div class="col-sm-12" style="float: right;">
                          <div class="btn-group btn-group-sm btn-group" style="margin-right: 5px; margin-top: 5px;">
                            <button type="button" class="btn btn-primary"
                              style="margin-right: 3px; margin-top: 2px; width: 75px;" (click)="delete()">Delete</button>
                            <button type="button" class="btn btn-primary"
                              style="margin-right: 3px; margin-top: 2px; width: 75px;">Update</button>
                            <button type="button" class="btn btn-primary"
                              style="margin-right: 3px; margin-top: 2px; width: 75px;"
                              (click)="getCardsList()">Load</button>
                            <label style="margin-right: 3px; margin-top: 2px; width: 75px;">Search: </label>
                            <input type='text' style="margin-right: 3px; margin-top: 2px; width: 150px; height: 30px;"
                              placeholder='Search with No' (keyup)='updateFilter($event)' />
                          </div>
                        </div>
                      </div><br>
                      <ngx-datatable #table class="data-table" [rows]="cards" [columnMode]="'force'" [scrollbarH]="true"
                        [columns]="columns" [headerHeight]="40" [footerHeight]="40" [rowHeight]="'auto'" [limit]="10"
                        [selected]="selected" [selectionType]="'single'" (activate)="onActivate($event)"
                        (select)='onSelect($event)'>
                      </ngx-datatable><br>
                      <div class="row">
                        <div class='col-sm-12 selected-column'>
                          <h4 class="sub-title p-t-15">Selected Row</h4>
                          <ul>
                            <li *ngFor='let card of selected'>
                              <span class="label label-primary">{{card.no}}</span>
                            </li>
                            <li *ngIf="!selected.length">No Selections</li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </ng-template>
              </ngb-tab>
            </ngb-tabset>
          </div>
        </div>
      </div>
    </app-card>
  </div>
</div>

Внутренняя сторона

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ImperaxTrack.Datas;
using ImperaxTrack.Dtos;
using ImperaxTrack.Helpers;
using ImperaxTrack.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ImperaxTrack.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    public class CardsController : ControllerBase
    {
        private readonly IAppRepository _appRepository;
        private readonly IMapper _mapper;

        public CardsController(IAppRepository appRepository, IMapper mapper)
        {
            _appRepository = appRepository;
            _mapper = mapper;
        }

        [HttpGet("")]
        public ActionResult GetCardsList()
        {
            var cards = _appRepository.GetCardsList().Where(c=>c.IsActive == IsActiveEnum.Active);
            var cardsToReturn = _mapper.Map<List<CardForListDto>>(cards);
            return Ok(cardsToReturn);
        }

        //[HttpPost("")]
        //[Route("add")]
        //public ActionResult Add(Card card)
        //{
        //    card.CreatedDate = DateTime.UtcNow;
        //    card.IsActive = IsActiveEnum.Active;
        //    _appRepository.Add(card);
        //    _appRepository.SaveAll();
        //    return Ok("Record is added");
        //}

        [HttpPost("")]
        [Route("add")]
        public async Task<IActionResult> Add([FromBody] Card card)
        {
            var cardToCreate = new Card
            {
                CreatedDate = DateTime.UtcNow,
                IsActive = IsActiveEnum.Active,
                No = card.No
            };
            await _appRepository.Add(cardToCreate);
            return StatusCode(201);
        }

        [HttpPut("")]
        [Route("update")]
        public ActionResult Update(Card card)
        {
            var IsActiveControl = _appRepository.GetCardById(card.Id).IsActive;
            if (IsActiveControl == IsActiveEnum.Deleted || IsActiveControl == IsActiveEnum.Passive)
            {
                return BadRequest("Record already was deleted or passive");
            }
            else
            {
                var foundcreatedDate = _appRepository.GetCardById(card.Id).CreatedDate;
                card.CreatedDate = foundcreatedDate;
                card.IsActive = IsActiveEnum.Active;
                card.UpdatedDate = DateTime.UtcNow;
                _appRepository.Update(card);
                _appRepository.SaveAll();
                return Ok("Record is updated");
            }
        }

        [HttpDelete("")]
        [Route("delete")]
        public ActionResult Delete(Card card)
        {
            var IsActiveControl = _appRepository.GetCardById(card.Id).IsActive;
            if (IsActiveControl != IsActiveEnum.Active)
            {
                return BadRequest("Record already was deleted or passive");
            }
            else
            {
                var foundcreatedDate = _appRepository.GetCardById(card.Id).CreatedDate;
                card.CreatedDate = foundcreatedDate;
                card.IsActive = IsActiveEnum.Deleted;
                card.UpdatedDate = DateTime.UtcNow;
                _appRepository.Update(card);
                _appRepository.SaveAll();
                return Ok("Record is deleted");
            }

        }
    }
}

сообщение об ошибке

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...