Hi guys, I'm fairly new to angularjs 2 (I've only used 2) and I have a small application with a form. Currently I'm able to get the form data as an objects and print it to the console.log,

onSubmit(form: any):void{
       console.log(form);
   }

producing this:

Object {author: "Author test", title: "Title test", location: "Location test", medium: "Medium test", notes: "Notes test"}

but what I want to do now is to push that data to a mysql database. I have no idea what needs to be done, so I'm doing a bit of reading here and there, but I have to say I didn't find that much useful info: often they do it in angularjs rather than angularjs 2, so I'm not sure that applies to me. So, generally speaking, what do I need? Do I need to convert the object to Json or is it good to go as it is? If you guys have any suggestions or links for me to read, then please fire away
cheers

Dani AI

Generated

A short, practical summary for : a browser-based Angular app cannot talk directly to a MySQL server. As noted, introduce a server-side web service (a simple REST endpoint) that accepts the form payload and performs the database insert. The backend can be in Node/Express, PHP (PDO), Python/Flask, etc.—pick whatever runtime is familiar.

No manual conversion to a string is necessary in most cases. When using Angular's HTTP helpers the plain form object can be sent and will be serialized to JSON; the server must parse JSON (for example Express uses express.json(), PHP can use json_decode(file_get_contents('php://input'))). Always validate and sanitize server-side and use parameterized queries to avoid SQL injection.

Example workflow and minimal code (Angular front end + Node/Express backend):

/* Angular (recommended HttpClient) */
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

submitBook(book) {
  this.http.post('/api/books', book)
    .subscribe(
      (res: any) => console.log('saved', res),
      err => console.error(err)
    );
}
/* Node/Express + mysql2 (server) */
app.use(express.json());
app.post('/api/books', async (req, res) => {
  const { title, author, location, medium, notes } = req.body;
  const [result] = await pool.execute(
    'INSERT INTO books (title, author, location, medium, notes) VALUES (?, ?, ?, ?, ?)',
    [title, author, location, medium, notes]
  );
  res.json({ id: result.insertId });
});

SQL table example:

CREATE TABLE books (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  author VARCHAR(255),
  location VARCHAR(255),
  medium VARCHAR(100),
  notes TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Troubleshooting and cautions: test the API first with curl or Postman; enable CORS when front end and API are on different origins; ensure Content-Type: application/json; do not store DB credentials in code (use environment variables); use connection pooling and proper error handling. If still on older Angular 2 releases, use the @angular/http service, but prefer HttpClient from @angular/common/http where available.

Recommended Answers

All 2 Replies

Is this a mobile app or running ina browser?
If a mobile app you'll need to make an HTTP call to an endpoint to pass the data through so the server has the data to work with. From there how you proceed will depend on which language/platform you are using (C#, Jave, Node, etc).

A little more information about your setup would help.

It will be running in a browser.
So, here are a few more details.
The application is essentially meant to allow users to input books (Title, author and a few more fields) using a form and when the form is submitted all that data go to a database (mySql).
Currently I have only the frontend part, done entirely in angularjs 2.
I've never really stored any application data in a database before, so I'm really not sure what approach to take.
I've done more readings since after this post, and it turns out that, as you're pointing out, I need another layer, something like a webservice that takes the data from my application - which is now in Json - and sends it to the database.
After that I will have to retrieve that data too, but one thing at the time, let's think about how to send it and store it to the database first.
If you want to have a look at some code it's all in here https://github.com/Antobbo/Books-Proj-last/tree/master/src/app, if you want some specific bits, please do let me know

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.