Wednesday, April 5, 2023

Connect Your Angular App to MySQL Database for IMCA,BCA,MCA and all IT Students

 


Prepared By : Uday Shah (HOD-IT)

Contact No : 7600044051

----------------------------------------------------------------------------------------------------------------------------

Tutorial: Connect Your Angular App to MySQL


In this post, see how to create an Angular application using MySQL that will let the user edit and add events using a CRUD API.

MySQL is an open-source relational database that can deliver high-performance, scalable database applications. As the M in the LAMP stack, it is a powerhouse for a lot of web servers across the globe. With MySQL, data is stored in tables with strict data definitions, and rows in tables reflect data entries and through the index. There’s a lot of documentation that covers best practices and the basics of SQL for developing relational databases for huge applications.

In this post, I’ll walk you through creating an Angular application using MySQL that will let the user edit and add events using a CRUD API. We’ll use a version of the MEAN stack, where the M will stand for the MySQL database, Express.js for the backend, and Angular.js for the client.

I will assume that you have some familiarity with Node and the npm package manager and that both of these are installed on your system.

Setting up MySQL

If you don’t have installed MySQL on your system, follow the instructions on the MySQL website to do so. Depending on your operating system, you might be able to use the system’s package manager to install the MySQL server.

Once you have installed MySQL, you can create the database that you will use in this tutorial. Log into the database using the MySQL client using the login details of the database administrator.


The -p option indicates that you are required to supply a password when connecting to the MySQL server. You might not need this option, depending on how the database is set up on your system. You should now see the MySQL command line prompt.


Create a new database and switch into it by using the following command.


Next, create a user associated with this database. It is always a good idea to have separate users for each database on the system. The following commands will create the user and grant them all permissions on the timeline database.


In the first line, replace password with a more complex password. The rest of this tutorial assumes you used “password”, so if you change it, please make sure and change it in all the code snippets below.

Now you are ready to create the events table in the new database by specifying the data schema.


The table contains several columns called idownernamedescription, and date. The id column acts as the primary key for accessing individual rows. Since you will need to look up entries by owner and date,I added a secondary index using these two fields to speed up the lookup. This completes the setup of the database, and you can now exit the MySQL client by using the quit command.

Set up a Simple CRUD Node Express Server

To create the Express server, navigate into a directory of your choice and create a new folder called timeline-server. Open a terminal in this directory and initialize the Node project using npm.


Answer all the questions using the default answer and when asked about the entry point, set it to src/index.js. Next, install some libraries you will need.


Next, use your favorite editor and create a file src/index.js and paste the following code into it.


At the top of the file, you can see several imports. express contains the Express framework for creating REST APIs, cors is a middleware responsible for allowing cross-origin requests, and body-parser makes sure that the bodies of the incoming requests are read and attached to the request object.

The mysql object allows us to connect to your MySQL database and is seen in the code immediately below the require statements. In the options to createConnection, you will need to replace password with the password that you have stored in your MySQL server above. In the bottom part of src/index.js, the Express server is configured with the middleware and the events router and then started.

The last require statement imports the events router. To create the router, create a new file called src/events.js and paste the following code.


This piece of code defines a function that takes the database connection as an argument and creates a router. I deliberately left the main part of the function blank. Soon, you will define the individual routes of the REST API in this block. I also defined an empty string called owner to use as a placeholder for the owner column in the database. In the next section, I will show you how to obtain the user’s email address and use this to identify the owner.

The first route will insert new events into the database. Paste the following into the body of the createRouter() function.


By using router.post this route will only activate when the server receives an HTTP POST request. The data posted in the request can be obtained through the req.body object. Using the SQL INSERT statement, this code adds a new row to the events table.

To list the events of a single owner, the following route links an HTTP GET request to a MySQL SELECT statement. You can paste this code into the body of the createRouter() function right after the previous route.


You can also modify existing entries in the database with a PUT route, which links an HTTP PUT request to a MySQL UPDATE statement.


The code obtains the id as a route parameter from the req.params object.

Finally, you might want to delete an existing event. Do this through an HTTP DELETE request that issues a MySQL DELETE statement.


Run Your Express App and Connect to MySQL

The code above implements a fully functioning server. You can run this server by opening the terminal in the project directory and running the following command.


You might see the following error when you run this command:


To fix this, log into MySQL and execute the following SQL (where password is the value you used for your password):


Authentication With JWT

In this section, I will show you how to use JWT and Okta to authenticate users to your application. User authentication is an important part of any web app, but developers often underestimate the effort required to safely implement and maintain secure authentication. With Okta, you can offload all the complexity and security considerations to an external provider.

To start, sign up for a free developer account with Okta. After completing your registration, you will see your Okta dashboard.

To create a new application, select the Applications link in the top menu, and click on the green Add Application button. Next, you will see a screen with several options. Select Single-Page App and click Next.

The next screen lets you edit the application settings. For the client you will use Angular, so make sure that the base URI points to http://localhost:4200/. You will also need to set the Login Redirect URI to http://localhost:4200/implicit/callback, where the user will be redirected after a successful login. After you click the Done button, you will see a screen with a client ID you will need below.

To use Okta authentication in your server app, you need to install some additional libraries. In the terminal, run the following command:


Next, create a new file src/auth.js and paste the following code.


This module defines an Express middleware that reads a token from the request and verifies it using the Okta JWT Verifier. In the code above, {yourClientId} is the client ID you obtained from the Okta application settings and {yourOktaDomain} is your Okta domain. When the user authenticates successfully, a user object containing the user ID and email will be added to the request.

Open src/index.js again and add the following require statements to the top of the file.


Now modify the Express application configuration to include the bearerToken and oktaAuth middlewares.


Finally, modify the event route to make use of the user email. In src/events.js, remove the line const owner = ''; and add const owner = req.user.email; to the first line in each router block:


These changes secure your server application. It also stores events for users separately, and each user will only see their own events.

The Timeline Angular Client

Now it’s time to implement the client application based on Angular 8 with the ngx-bootstrap library for responsive layout and standard components. You will also use a free icon set called Line Awesome, a variant of the well known Font Awesome that replaces the standard icon designs with some stylish line icons. You will also use the ngx-timeline library to make it easy to create beautiful vertical timelines.

To start, you will need to install the latest version of the Angular CLI tool. In a terminal, type the following command.


Depending on your system, you might have to run this command using sudo to allow modification of system resources. Next, navigate into a directory of your choice and create a new Angular application.


You will be asked a number of questions about your applications. Make sure that you add the Angular routing module.


When asked which stylesheet format to use, choose the default CSS option. Now change into the new folder timeline-client and install some additional packages. Add Bootstrap with the ng add command.


To add the timeline library and Okta’s Angular SDK, run the following command:


Now start your IDE and open up the file src/index.html. Here, add some external CSS files inside the <head> tags to add styles for Bootstrap and Line Awesome:


Open src/app/app.component.ts and replace the contents with the following code.


The AppComponent handles the authentication through Okta. OktaAuthService.isAuthenticated() initializes the isAuthenticated field of the component. The field is kept up to date by subscribing to the OktaAuthService.$authenticationState observable. OktaAuthService.loginRedirect() will trigger a browser redirect to the Okta login page and OktaAuthService.logout('/') will log out the user and navigate to the '/' route.

Now open the template of the application component src/app/app.component.html and paste in the following HTML.


The bootstrap navigation bar contains a menu with links to the home page and a timeline route. It also contains a login button and a logout button that appear depending on the authentication state.

In the next step, you need to import the component modules into src/app/app.module.ts. It looks like this:


Replace{yourClientId} with the client ID from your Okta dashboard and {yourOktaDomain} with your Okta domain. Next, create two components for the home page and the timeline page, as well as a service to connect to the server.


The home page will simply contain a heading and no other functionality. Open src/app/home/home.component.html and replace the contents with the following.


Now open src/app/home/home.component.css and add the following styles.


Before you implement the timeline component, let’s take a look at the ServerService first. Open src/app/server.service.ts and replace the contents with the following code.


The main logic of this component resides in the request method, which sends a request to the server. To identify the user to the server, the request header contains a bearer token obtained from OktaAuthService. The method returns a Promise that resolves once a response from the server has been obtained.

The remainder of the ServerService uses the request method to call the server routes. The server URL is provided through the environment object, which is defined in src/environments/environment.ts.


The comments in src/environments/environment.ts provide useful hints about how to use environments in Angular.

Now you are ready to implement the timeline component. Open src/app/timeline/timeline.component.html and edit the contents to match the code below.


This template uses the ngx-timeline component to display an array of events in a vertical timeline, with buttons for adding and editing events. Some of these actions will open up a modal window. ngx-bootstrap allows you to simply create a modal window from an ng-template component. Paste the following code into the bottom of the file.


Only a small amount of styling in src/app/timeline/timeline.component.css rounds off the design.


The src/app/timeline/timeline.component.ts file contains the bulk of the application logic.


I will not go into every detail of this code. The methods addEvent()editEvent(), and deleteEvent() are the event handlers for the respective HTML buttons. addEvent() and editEvent() open the modal window and set either createEvent() or updateEvent() as a callback function when the user submits data. These use the ServerService to complete the request.

Finally, link the components to the routes. Open src/app/app-routing.module.ts and add the following import statements to the top of the file.


Next, replace the routes array with the following.


The first entry sets the base route and links it to the HomeComponent. The second entry links the timeline route to the TimelineComponent and prevents unauthorized access to the route with OktaAuthGuard. When a user authenticates via the Okta service, they will be redirected to the implicit/callback route.

Run Your Angular Client Application

This completes the implementation of the client. You can start the client from the terminal by running this command.


Make sure that you have also started the server, as described in the previous section. Open a browser to http://localhost:4200. Log in, click on Timeline in the top menu, and add events to your heart’s content.