Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How to Create and Use Services in Angular for Data Handling

Hey friends! Leela here, and welcome to another blog post about Angular. If you’ve been following along, in the previous tutorial, we discussed dependency injection for services and how we can inject a service into our Angular components. Today,

we’re diving deeper into how we can use a service as a central hub for managing data and pass that data to components.

Setting Up a New Angular Project

To start, let’s set up a new Angular project. Once the setup is complete, you’ll see the default output on your browser.

Now, we’ll create two components for this project—UserComponent and AddUserComponent—which will interact with the data stored in our service.

You can create components by running the following Angular CLI commands:

ng generate component user
ng generate component add-user

Adding Bootstrap for Styling

Next, we’ll add Bootstrap to our Angular project for styling purposes. If you already have Bootstrap installed in your system, great! If not, run the following command:

npm install bootstrap

After installation, go to angular.json and include the Bootstrap CSS file in the styles section:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Now, restart your development server for the changes to take effect.

Creating a Service for User Data

The core of this tutorial is creating a service to manage our user data. To create a service, run the following command:

ng generate service user

In the user.service.ts file, we’ll define a simple service to hold our user data:

export class UserService {
  users = [
    { name: 'Leela', status: 'active' },
    { name: 'Linda', status: 'inactive' }
  ];

  addUser(name: string, status: string) {
    this.users.push({ name, status });
  }
}

This service has an array of users, each with a name and status. We also defined a method addUser to allow new users to be added to the list.

Injecting the Service into Components

To access the service’s data, we’ll inject it into the AppComponent and other components. Let’s start by injecting it into AppComponent:

import { UserService } from './services/user.service';

export class AppComponent {
  users: {name: string, status: string}[] = [];

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.users = this.userService.users;
  }
}

Here, we use dependency injection to bring the UserService into the component. The ngOnInit method ensures that when the component initializes, it grabs the list of users from the service.

Displaying User Data in the Template

Now that we have the user data available in our AppComponent, let’s display it in the template (app.component.html):

<div class="container">
  <div class="row">
    <div *ngFor="let user of users" class="col-md-4">
      <app-user [user]="user"></app-user>
    </div>
  </div>
</div>

In this code, we are looping through the users array and passing each user to the UserComponent as an input property.

Working with Input Properties

Let’s handle the input property in the UserComponent. First, define the @Input() decorator to accept the user data:

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  @Input() user: { name: string, status: string };
}

In the user.component.html file, we can now display the user’s name and status:

<div>
  <h4>{{ user.name }}</h4>
  <p>Status: {{ user.status }}</p>
</div>

Adding New Users with a Form

To add new users, let’s create a form in AddUserComponent. In the template (add-user.component.html), add a simple form:

<form (ngSubmit)="onAddUser()">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" [(ngModel)]="newUser.name" class="form-control" required>
  </div>
  <button type="submit" class="btn btn-primary">Add User</button>
</form>

In the component logic (add-user.component.ts), we’ll handle the form submission:

export class AddUserComponent {
  newUser = { name: '', status: 'active' };

  constructor(private userService: UserService) {}

  onAddUser() {
    this.userService.addUser(this.newUser.name, this.newUser.status);
  }
}

Handling User Status Updates

We can also add functionality to update user statuses. In the UserComponent, add buttons for setting a user’s status to “active” or “inactive”:

<button (click)="setStatus('active')" class="btn btn-success">Set Active</button>
<button (click)="setStatus('inactive')" class="btn btn-danger">Set Inactive</button>

In the component logic:

setStatus(newStatus: string) {
  this.user.status = newStatus;
}

Wrapping It Up

And that’s it! We’ve successfully created an Angular app where we use a service as a data source and inject that service into multiple components. This allows us to centralize data management and update it efficiently.

By using Angular’s dependency injection, data-binding, and forms, you can build robust and dynamic applications. Keep experimenting with new features, and stay tuned for more Angular tips in future blog posts!