我想用选择单选按钮将我的数据传递到数据库

问题描述 投票:0回答:0

我有 4 个单选按钮(新闻、生日、周年纪念、讣告),当我从中选择任何人时,数据应该传递给那个特定的单选按钮,但它不会通过选定的特定单选按钮传递,它只在新闻中传递,而不是其他单选按钮.

这是我的角度代码。

<div class="box1">
                        <input type="radio" name="category" value="news" data-category="news"> News
                        <input type="radio" name="category" value="obituary" data-category="obituary"> Obituary
                        <input type="radio" name="category" value="birthday" data-category="birthday"> Birthday
                        <input type="radio" name="category" value="anniversary" data-category="anniversary"> Anniversary
                      </div>

我的ts文件

import { Component,OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ApiserviceService } from '../apiservice.service';
@Component({
  selector: 'app-newsform',
  templateUrl: './newsform.component.html',
  styleUrls: ['./newsform.component.css']
})
export class NewsformComponent implements OnInit {
  newsRadioChecked = true;
obituaryRadioChecked = false;
birthdayRadioChecked = false;
anniversaryRadioChecked = false;
onCategoryChange(event: Event) {
  const target = event.target as HTMLInputElement;
  const category = target.dataset['category'];
  switch (category) {
    case 'news':
      this.newsRadioChecked = true;
      this.obituaryRadioChecked = false;
      this.birthdayRadioChecked = false;
      this.anniversaryRadioChecked = false;
      break;
    case 'obituary':
      this.newsRadioChecked = false;
      this.obituaryRadioChecked = true;
      this.birthdayRadioChecked = false;
      this.anniversaryRadioChecked = false;
      break;
    case 'birthday':
      this.newsRadioChecked = false;
      this.obituaryRadioChecked = false;
      this.birthdayRadioChecked = true;
      this.anniversaryRadioChecked = false;
      break;
    case 'anniversary':
      this.newsRadioChecked = false;
      this.obituaryRadioChecked = false;
      this.birthdayRadioChecked = false;
      this.anniversaryRadioChecked = true;
      break;
    default:
      break;
  }
}



  errmsg: any;
  selectedFile!: File;
  readData: any;
  constructor(private service:ApiserviceService){}
  ngOnInit(): void {
  }
  newsForm = new FormGroup({
    headline: new FormControl('',Validators.required),
    news: new FormControl('',Validators.required),
    path: new FormControl(null,Validators.required),
    currentdate: new FormControl(this.getCurrentDate()),
    expirydate: new FormControl(this.validateExpiryDate()),
  });
  successmsg: any;  
  getCurrentDate(): string {
    const currentDate = new Date();
    currentDate.setDate(currentDate.getDate());
    const year = currentDate.getFullYear();
    const month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
    const day = ('0' + currentDate.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
}
  validateExpiryDate(): string{
    const currentdate = new Date();
    const expirydate = new Date(currentdate.getTime());
    expirydate.setDate(currentdate.getDate() + 15);
    if (expirydate <= currentdate) {
      expirydate.setDate(currentdate.getDate() + 15);
    }
    const year = expirydate.getFullYear();
    const month = ('0' + (expirydate.getMonth() + 1)).slice(-2);
    const day = ('0' + expirydate.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
  }
  getMinDate(): string {
    const currentdate = new Date();
    currentdate.setDate(currentdate.getDate() + 15);
    const year = currentdate.getFullYear();
    const month = ('0' + (currentdate.getMonth() + 1)).slice(-2);
    const day = ('0' + currentdate.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
  }
  onfileSelected(event: any) {
    this.selectedFile = event.target.files[0];
  }

  
  Submit() {
    if (this.newsForm.valid) {
      const formData = new FormData();
      const headline = this.newsForm.get('headline')?.value ?? '';
      const news = this.newsForm.get('news')?.value ?? '';
      const currentdate = this.newsForm.get('currentdate')?.value ?? '';
      const expirydate = this.newsForm.get('expirydate')?.value ?? '';
      const id = this.newsForm.get('id')?.value ?? '';
      
  
      if (headline || news || currentdate || expirydate || this.selectedFile) {
        formData.append('headline', headline);
        formData.append('news', news);
        formData.append('currentdate', currentdate);
        formData.append('expirydate', expirydate);
        formData.append('id', id);
        formData.append('path', this.selectedFile, this.selectedFile.name); // don't include id in the filename here
      }
      console.log(formData)
     
      if (this.newsRadioChecked) {
        this.service.NewsformData(formData).subscribe(
          (res) => {
            console.log(res);
            this.newsForm.reset();
            this.successmsg = res.message;
            const insertedId = res.id; // get the id from the server response
            // use the id to set the filename of the selected file
            this.selectedFile = new File(
              [this.selectedFile],
              `${insertedId}.${this.selectedFile.name.split('.').pop()}`,
              { type: this.selectedFile.type }
            );
          },
          (err) => {
            console.error(err);
            this.errmsg = 'Error uploading file';
          }
        );
      } else if (this.obituaryRadioChecked) {
        this.service.ObituaryformData(formData).subscribe(
          (res) => {
            console.log(res);
            this.newsForm.reset();
            this.successmsg = res.message;
            const insertedId = res.id; // get the id from the server response
            // use the id to set the filename of the selected file
            this.selectedFile = new File(
              [this.selectedFile],
              `${insertedId}.${this.selectedFile.name.split('.').pop()}`,
              { type: this.selectedFile.type }
            );
          },
          (err) => {
            console.error(err);
            this.errmsg = 'Error uploading file';
          }
        );
      } else if (this.birthdayRadioChecked) {
        this.service.BirthdayformData(formData).subscribe(
          (res) => {
            console.log(res);
            this.newsForm.reset();
            this.successmsg = res.message;
            const insertedId = res.id; // get the id from the server response
            // use the id to set the filename of the selected file
            this.selectedFile = new File(
              [this.selectedFile],
              `${insertedId}.${this.selectedFile.name.split('.').pop()}`,
              { type: this.selectedFile.type }
            );
          },
          (err) => {
            console.error(err);
            this.errmsg = 'Error uploading file';
          }
        );
      } else if (this.anniversaryRadioChecked) {
        this.service.AnniversaryformData(formData).subscribe(
          (res) => {
            console.log(res);
            this.newsForm.reset();
            this.successmsg = res.message;
            const insertedId = res.id; // get the id from the server response
            // use the id to set the filename of the selected file
            this.selectedFile = new File(
              [this.selectedFile],
              `${insertedId}.${this.selectedFile.name.split('.').pop()}`,
              { type: this.selectedFile.type }
            );
          },
          (err) => {
            console.error(err);
            this.errmsg = 'Error uploading file';
          }
        );
      } else {
        this.errmsg = 'All fields are required';
      }
    }
  }  
}

我的api服务文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ApiserviceService {

  constructor(private http:HttpClient) { }

  apiUrl = "http://localhost:3000/register"

  getAllData():Observable<any>{
    return this.http.get(`${this.apiUrl}`)
  }
  createData(data:any):Observable<any>{
    return this.http.post(`${this.apiUrl}`,data)
  }
  UpdateData(data:any,id:any):Observable<any>{
    return this.http.put(`${this.apiUrl}/${id}`,data)
  }
  deleteData(id:any):Observable<any>{
    return this.http.delete(`${this.apiUrl}/${id}`)
  }
  getSingleData(id:any):Observable<any>{
    return this.http.get(`${this.apiUrl}/${id}`)
  }
  LoginData(data:any):Observable<any>{
    return this.http.post(`http://localhost:3000/login`,data)
  }
  NewsformData(data:any):Observable<any>{
    return this.http.post(`http://localhost:3000/newsform`,data)
  }
  Newsformget():Observable<any>{
    return this.http.get('http://localhost:3000/newsform')
  }
  BirthdayformData(data:any):Observable<any>{
    return this.http.post(`http://localhost:3000/birthdayform`,data)
  }
  AnniversaryformData(data:any):Observable<any>{
    return this.http.post(`http://localhost:3000/anniversaryform`,data)
  }
  ObituaryformData(data:any):Observable<any>{
    return this.http.post(`http://localhost:3000/obituaryform`,data)
  }
}


**My Nodejs backend file**

const upload2 = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
// Set the destination folder for uploaded files
cb(null, 'uploads/birthdayimage/');
},

    filename: function (req, file, cb) {
      const id = req.body.id;
      const originalName = file.originalname;
      const extension = originalName.split('.').pop();
      const newName = id + '.' + extension; // use the id to construct the filename
      cb(null, newName);
    },
  }),
});
const fs1 = require('fs');


app.post('/birthdayform', upload2.single('path'), (req, res) => {
  const headline = req.body.headline;
    const news = req.body.news;
  const currentdate = req.body.currentdate;
  const expirydate = req.body.expirydate;
  const path = req.file ? req.file.path : '';

  // insert the form data into the database
  const sql = 'INSERT INTO birthdayform (headline, news, path, currentdate, expirydate) VALUES (?, ?, ?, ?, ?)';
  db.query(sql, [headline, news, path, currentdate, expirydate], (err, result) => {
    if (err) {
      console.error('Error inserting data into the database: ', err);
      res.status(500).json({ message: 'Error inserting data into the database' });
    } else if (result.affectedRows === 0) {
      console.error('Error inserting data into the database: no rows affected');
      res.status(500).json({ message: 'Error inserting data into the database: no rows affected' });
    } else {
      console.log('Data inserted into the database');
      const id = result.insertId;
      const extension = path.split('.').pop();
      const filename = `${id}.${extension}`;
      const newPath = `${path.slice(0, -extension.length)}${filename}`;
      fs1.renameSync(path, newPath); // rename the file with the new filename

      // update the path of the image in the database
      const sqlUpdate = 'UPDATE birthdayform SET path = ? WHERE id = ?';
db.query(sqlUpdate, [`uploads/birthdayimage/${filename}`, id], (err, result) => {
if (err) {
  console.error('Error updating path in the database: ', err);
  res.status(500).json({ message: 'Error updating path in the database' });
} else {
  console.log('Path updated in the database');
  res.status(200).json({ message: 'Data inserted into the database', id, filename }); // send the id and filename back to the client
}
});

    }
  });
});



const upload3 = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
// Set the destination folder for uploaded files
cb(null, 'uploads/obituaryimage/');
},

    filename: function (req, file, cb) {
      const id = req.body.id;
      const originalName = file.originalname;
      const extension = originalName.split('.').pop();
      const newName = id + '.' + extension; // use the id to construct the filename
      cb(null, newName);
    },
  }),
});
const fs2 = require('fs');


app.post('/obituaryform', upload3.single('path'), (req, res) => {
  const headline = req.body.headline;
    const news = req.body.news;
  const currentdate = req.body.currentdate;
  const expirydate = req.body.expirydate;
  const path = req.file ? req.file.path : '';

  // insert the form data into the database
  const sql = 'INSERT INTO obituaryform (headline, news, path, currentdate, expirydate) VALUES (?, ?, ?, ?, ?)';
  db.query(sql, [headline, news, path, currentdate, expirydate], (err, result) => {
    if (err) {
      console.error('Error inserting data into the database: ', err);
      res.status(500).json({ message: 'Error inserting data into the database' });
    } else if (result.affectedRows === 0) {
      console.error('Error inserting data into the database: no rows affected');
      res.status(500).json({ message: 'Error inserting data into the database: no rows affected' });
    } else {
      console.log('Data inserted into the database');
      const id = result.insertId;
      const extension = path.split('.').pop();
      const filename = `${id}.${extension}`;
      const newPath = `${path.slice(0, -extension.length)}${filename}`;
      fs2.renameSync(path, newPath); // rename the file with the new filename

      // update the path of the image in the database
      const sqlUpdate = 'UPDATE obituaryform SET path = ? WHERE id = ?';
db.query(sqlUpdate, [`uploads/obituaryimage/${filename}`, id], (err, result) => {
if (err) {
  console.error('Error updating path in the database: ', err);
  res.status(500).json({ message: 'Error updating path in the database' });
} else {
  console.log('Path updated in the database');
  res.status(200).json({ message: 'Data inserted into the database', id, filename }); // send the id and filename back to the client
}
});

    }
  });
});






const upload4 = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
// Set the destination folder for uploaded files
cb(null, 'uploads/anniversaryimage/');
},

    filename: function (req, file, cb) {
      const id = req.body.id;
      const originalName = file.originalname;
      const extension = originalName.split('.').pop();
      const newName = id + '.' + extension; // use the id to construct the filename
      cb(null, newName);
    },
  }),
});
const fs3 = require('fs');


app.post('/anniversaryform', upload4.single('path'), (req, res) => {
  const headline = req.body.headline;
    const news = req.body.news;
  const currentdate = req.body.currentdate;
  const expirydate = req.body.expirydate;
  const path = req.file ? req.file.path : '';

  // insert the form data into the database
  const sql = 'INSERT INTO anniversaryform (headline, news, path, currentdate, expirydate) VALUES (?, ?, ?, ?, ?)';
  db.query(sql, [headline, news, path, currentdate, expirydate], (err, result) => {
    if (err) {
      console.error('Error inserting data into the database: ', err);
      res.status(500).json({ message: 'Error inserting data into the database' });
    } else if (result.affectedRows === 0) {
      console.error('Error inserting data into the database: no rows affected');
      res.status(500).json({ message: 'Error inserting data into the database: no rows affected' });
    } else {
      console.log('Data inserted into the database');
      const id = result.insertId;
      const extension = path.split('.').pop();
      const filename = `${id}.${extension}`;
      const newPath = `${path.slice(0, -extension.length)}${filename}`;
      fs3.renameSync(path, newPath); // rename the file with the new filename

      // update the path of the image in the database
      const sqlUpdate = 'UPDATE anniversaryform SET path = ? WHERE id = ?';
db.query(sqlUpdate, [`uploads/anniversaryimage/${filename}`, id], (err, result) => {
if (err) {
  console.error('Error updating path in the database: ', err);
  res.status(500).json({ message: 'Error updating path in the database' });
} else {
  console.log('Path updated in the database');
  res.status(200).json({ message: 'Data inserted into the database', id, filename }); // send the id and filename back to the client
}
});

    }
  });
});

请帮我看看哪里出错了

mysql node.js angular
© www.soinside.com 2019 - 2024. All rights reserved.