Implementing Backend Services in Angular
Implementing Backend Services in Angular
Prerequisites:
• Angular CLI
• Node.js and npm
• Basic understanding of Angular and Node.js
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
getData() {
return this.http.get('/api/data');
}
}
@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);
});
}
}
Open your browser at localhost:4200 and navigate to /api/data. You should see the message
"Hello, world!".
Additional Notes:
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:
npm init -y
npm install express
2. Create a new file called server.js and add the following code:
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.
node server.js
Frontend (Angular):
ng new my-app
ng add @angular/http
3. Create a new file called users.service.ts and add the following code:
getUsers(): Promise<any[]> {
return this.http.get(this.usersUrl);
}
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:
@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 = [];
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.
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.