0% found this document useful (0 votes)
32 views

Implementing Backend Services in Angular

The document outlines steps to implement a backend API using Node.js and Express and connect it to an Angular frontend. It describes setting up an Express server with GET and POST routes, creating an Angular service to consume the API, and using the service in a component.

Uploaded by

Reaper X
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Implementing Backend Services in Angular

The document outlines steps to implement a backend API using Node.js and Express and connect it to an Angular frontend. It describes setting up an Express server with GET and POST routes, creating an Angular service to consume the API, and using the service in a component.

Uploaded by

Reaper X
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Implementing Backend Services in Angular

Prerequisites:

• Angular CLI
• Node.js and npm
• Basic understanding of Angular and Node.js

Step 1: Set up the Angular project:


ng new my-angular-app

Step 2: Create a Node.js project:


npm install express

Step 3: Create a server.js file:


import express from 'express';

const app = express();


app.get('/api/data', (req, res) => {
res.send('Hello, world!');
});

app.listen(3000, () => {
console.log('Server listening on port 3000');
});

Step 4: Import the backend service in Angular:


import { HttpClient } from '@angular/common/http';

export class MyService {


constructor(private http: HttpClient) { }

getData() {
return this.http.get('/api/data');
}
}

Step 5: Use the service in your Angular component:


import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular with Node.js';
constructor(private service: MyService) { }

getData() {
this.service.getData().subscribe(data => {
console.log(data);
});
}
}

Step 6: Run the server and Angular application:


npm start
ng serve

Access the backend service:

Open your browser at localhost:4200 and navigate to /api/data. You should see the message
"Hello, world!".

Additional Notes:

• The above steps provide a basic implementation of a backend-Angular application.


You can customize the backend service to provide the data you need.
• You can use different HTTP methods (GET, POST, PUT, DELETE) to interact with your
backend service.
• For production use, you should consider security measures such as authentication
and authorization.

Resources:

• Angular HttpClient
• Node.js Express

Here's an example of how to implement a backend API using Node.js and Express, and
connect it to an Angular frontend:

Backend (Node.js and Express):

1. Create a new Node.js project and install Express:

npm init -y
npm install express
2. Create a new file called server.js and add the following code:

const express = require('express');


const app = express();

app.get('/users', (req, res) => {


const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
];
res.json(users);
});

app.post('/users', (req, res) => {


const { name } = req.body;
const id = Math.random() + 1;
const user = { id, name };
res.json(user);
});

app.listen(3000, () => {
console.log('Server started on port 3000');
});

This code sets up an Express server that listens on port 3000 and defines two
endpoints: /users and /users/{id}. The /users endpoint returns a list of users in JSON format,
while the /users/{id} endpoint creates a new user with the provided name and returns the new
user in JSON format.

3. Start the server:

node server.js

Frontend (Angular):

1. Create a new Angular project using the Angular CLI:

ng new my-app

2. Install the http module:

ng add @angular/http

3. Create a new file called users.service.ts and add the following code:

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class UsersService {
private usersUrl = 'http://localhost:3000/users';

constructor(private http: HttpClient) {}

getUsers(): Promise<any[]> {
return this.http.get(this.usersUrl);
}

createUser(name: string): Promise<any> {


const body = JSON.stringify({ name });
return this.http.post(this.usersUrl, body);
}
}

This code defines a service that provides an interface for interacting with the backend API. It
has two methods: getUsers() and createUser(). The getUsers() method makes a GET request to
the /users endpoint to retrieve a list of users, while the createUser() method makes a POST
request to the /users endpoint to create a new user.

4. In your component, inject the UsersService and call the getUsers() method to retrieve a
list of users:

import { Component } from '@angular/core';


import { UsersService } from './users.service';

@Component({
selector: 'app-root',
template: `
<div>
<h1>Users</h1>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
</div>
`,
})
export class AppComponent {
title = 'My App';
users = [];

constructor(private usersService: UsersService) {}

ngOnInit() {
this.usersService.getUsers().toPromise().then(users => {
this.users = users;
});
}
}

This code defines a component that displays a list of users. It injects the UsersService and calls
the getUsers() method in the ngOnInit() lifecycle hook to retrieve a list of users. The list of users
is then bound to a template using the ngFor directive.

5. Run the application:

ng serve

This will start the Angular development server and open the application in your browser
at http://localhost:4200. You should see a list of users displayed in the UI.

6. Create a new user:

In your browser, navigate to http://localhost:4200/users/new and enter a

You might also like