TÀI LIỆU HAY - CHIA SẺ KHÓA HỌC MIỄN PHÍ

Learn Angular 8 by creating a simple Full Stack Web App

Learn Angular 8 by creating a simple Full Stack Web App

Learn Angular 8 by creating a simple Full Stack Web App
Angular 8 is one of the most popular frameworks for developing web applications. It provides a robust, modular architecture, making it easy to create complex applications. In this article, we will explore how to learn Angular 8 by creating a simple full-stack web app.

Before we dive in, let's define what a full-stack web app is. It's an application that utilizes a front-end, a back-end, and a database. In our case, the front-end will be built with Angular 8, the back-end with Node.js and Express, and the database with MongoDB.

Now, let's get started with the steps you need to take to learn Angular 8 by creating a simple full-stack web app.

1. Set up your development environment:
The first step is to set up your development environment. You will need Node.js, Angular 8 CLI, and MongoDB installed. You can download Node.js from the official website, Angular CLI via npm, and MongoDB from its official website.

2. Create an Angular 8 project:
Open your terminal or command prompt and navigate to the directory where you want to create your Angular 8 project. Type the following command to create a new Angular 8 project:

```
ng new --routing
```

The `--routing` flag will generate a routing module for your application, which we will use later in our project.

3. Build a simple UI:
Next, we'll create a simple user interface for our application. Open the project directory in your favorite code editor and add a new component to the app folder using the Angular CLI command:

```
ng generate component home
```

This will generate a new component with a template, stylesheet, and TypeScript file. Open the home.component.html file and add some simple HTML markup to display a welcome message.

```

Welcome to my Full-Stack Web App!



```

4. Set up routing:
Now that we've built a simple UI, let's set up routing for our application. In the app-routing.module.ts file, insert the following code:

```
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```

This code will add a route to our application that maps to the HomeComponent we created in Step 3.

5. Build a backend REST API:
Now, let's build the backend of our full-stack web app. We'll create a REST API using Node.js and Express. In your project directory, create a new folder named `server` and initialize a new Node.js project in the folder using the following command:

```
npm init -y
```

Next, install Express using the following command:

```
npm install express --save
```

Create a new file named `index.js` and add the following code:

```
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
```

This code sets up a simple Express server that listens on port 3000 and returns the string "Hello World!" when the root route is accessed. You can run the server using the following command:

```
node index.js
```

Now, if you navigate to `http://localhost:3000`, you should see the "Hello World!" message.

6. Set up MongoDB:
In order to persist data for our full-stack web app, we'll use MongoDB. Head over to the official MongoDB website and download and install the Community Server for your operating system. Once installed, open the MongoDB shell and create a new database named "full-stack-web-app".

```
use full-stack-web-app
```

7. Create a data model:
Now, we'll create a data model for our MongoDB database. In the server directory, create a new folder named "models" and add a file named `user.js`. Add the following code:

```
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
}, {timestamps: true});
module.exports = mongoose.model('User', userSchema);
```

This code defines a user schema with name, email, and password fields that are required and adds a timestamp to the user's schema.

8. Connect the backend to MongoDB:
Now, we need to connect our Node.js server to MongoDB. We'll use the Mongoose library for this purpose. In your `index.js` file, add the following code:

```
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/full-stack-web-app', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.log('Error connecting to MongoDB', err);
});
```

This code connects our Node.js server to the "full-stack-web-app" database on our MongoDB server.

9. Build a REST API endpoint to create a user:
Next, we'll build a REST API endpoint to create a user. In your `index.js` file, add the following code:

```
const User = require('./models/user');
app.post('/api/users', (req, res) => {
const { name, email, password } = req.body;
const user = new User({ name, email, password });
user.save((err, user) => {
if (err) return res.status(400).send(err);
return res.status(200).send(user);
});
});
```

This code creates a new route for our server that listens for POST requests with a JSON payload containing name, email, and password fields. When a request is received, a new user is created and saved to MongoDB.

10. Use Angular 8 to create an HTML form:
Now, we'll create an HTML form in Angular 8 that will submit data to our Node.js server. In your home.component.html file, add the following code:

```

Create a new user


















```

This code creates an HTML form with fields for name, email, and password.

11. Handle form submissions in Angular 8:
We need to handle form submissions in Angular 8 and send the data to our Node.js server. In your home.component.ts file, add the following code:

```
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(private http: HttpClient) {}
onSubmit(event) {
event.preventDefault();
const name = event.target.elements.name.value;
const email = event.target.elements.email.value;
const password = event.target.elements.password.value;
const user = { name, email, password };
this.http.post('/api/users', user)
.subscribe((res) => {
console.log(res);
});
}
}
```

This code imports the HttpClient module from Angular, handles form submissions with the onSubmit method, extracts name, email, and password fields from the form data, builds a user object, and sends a POST request to the Node.js server using the HttpClient module.

12. Test your full-stack web app:
Start your Node.js server using the following command:

```
node index.js
```

Launch your Angular 8 application using the following command in your project directory:

```
ng serve
```

Navigate to `http://localhost:4200` in your browser and you should see the "Create a new user" form. Enter a name, email, and password and click the "Submit" button. Take a look at the console in your Node.js server and you should see a new user document in your "full-stack-web-app" MongoDB database.

Congratulations, you have successfully created a simple full-stack web app using Angular 8, Node.js, Express, and MongoDB! You have learned how to set up your development environment, create an Angular 8 project, build a simple user interface, set up routing, create a backend REST API, connect to MongoDB, build an HTML form, and handle form submissions. You can now build on this knowledge to create more complex full-stack web apps using Angular 8.
  • Mật khẩu giải nén: tailieuhay.download (nếu có)
  • Xem thêm các tài liệu về LẬP TRÌNH tại ĐÂY
  • Xem thêm các tài liệu về ANGULAR tại ĐÂY
BÁO LINK LỖI