Angular Learning : Practicing Services
Tags: angular, typescript, javascript, webdev
Published: 2021-07-13 04:48:27

Here we are having an angular app with 2 components, active users and inactive users. There are initially 2 active users and 2 inactive users. We can switch the users between active and inactive by using a clickable `Set to active` and `Set to inactive`. 
The objective is to create a service and obtain the same result.

## Active users code :

```typescript
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-active-users',
  templateUrl: './active-users.component.html',
  styleUrls: ['./active-users.component.css']
})
export class ActiveUsersComponent {
  @Input() users: string[];
  @Output() userSetToInactive = new EventEmitter<number>();

  onSetToInactive(id: number) {
    this.userSetToInactive.emit(id);
  }
}
```

```html
<h3>Active Users</h3>
<ul class="list-group">
  <li
    class="list-group-item"
    *ngFor="let user of users; let i = index">
    {{ user }} | <a href="#" (click)="onSetToInactive(i)">Set to Inactive</a>
  </li>
</ul>
```

So this component lists the user and there is a clickable which sets the user to inactive.

## Inactive users code :

```typescript
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-inactive-users',
  templateUrl: './inactive-users.component.html',
  styleUrls: ['./inactive-users.component.css']
})
export class InactiveUsersComponent {
  @Input() users: string[];
  @Output() userSetToActive = new EventEmitter<number>();

  onSetToActive(id: number) {
    this.userSetToActive.emit(id);
  }
}
```

```html
<h3>Inactive Users</h3>
<ul class="list-group">
  <li
    class="list-group-item"
    *ngFor="let user of users; let i = index">
    {{ user }} | <a href="#" (click)="onSetToActive(i)">Set to Active</a>
  </li>
</ul>
```

Same way as active users, here when the clickable is clicked, the user is sets to active.


## App component

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  activeUsers = ['Max', 'Anna'];
  inactiveUsers = ['Chris', 'Manu'];

  onSetToInactive(id: number) {
    this.inactiveUsers.push(this.activeUsers[id]);
    this.activeUsers.splice(id, 1);
  }

  onSetToActive(id: number) {
    this.activeUsers.push(this.inactiveUsers[id]);
    this.inactiveUsers.splice(id, 1);
  }
}
```


{% stackblitz services-demo-app file=src/index.html %}


## Making use of services :

We can obtain the same using services. All we have to do is create a new service and use these services in the component.

### Creating a new service

We can use the command `ng g s <servicename>` to create new service.

- user-service.service.ts
```typescript
import { Injectable } from '@angular/core';
import { CounterService } from './counter.service';

@Injectable({
  providedIn: 'root'
})
export class UserServiceService {

  constructor(private counterService : CounterService) { }

  activeUsers = ['Max', 'Anna'];
  inactiveUsers = ['Chris', 'Manu'];

  setToActive(id: number) {
    this.activeUsers.push(this.inactiveUsers[id]);
    this.inactiveUsers.splice(id, 1);
    this.counterService.incrementActiveToInactiveCounter();
  }

  setToInactive(id: number) {
    this.inactiveUsers.push(this.activeUsers[id]);
    this.activeUsers.splice(id, 1);
    this.counterService.incrementInActiveToActiveCounter();
  }
  
}
```
- counter.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class CounterService {

  activeToInactiveCounter = 0;
  inActiveToActiveCounter = 0;

  incrementActiveToInactiveCounter() {
    this.activeToInactiveCounter++;
    console.log("Active to Inactive Count:" + this.activeToInactiveCounter);
  }

  incrementInActiveToActiveCounter() {
    this.inActiveToActiveCounter++;
    console.log("Inactive to Active Count:" + this.inActiveToActiveCounter);
  }
  constructor() { }
}

```

- active-user-component.ts

```typescript
import { Component, OnInit } from '@angular/core';
import { UserServiceService } from '../user-service.service';

@Component({
  selector: 'app-active-users',
  templateUrl: './active-users.component.html',
  styleUrls: ['./active-users.component.css']
})
export class ActiveUsersComponent implements OnInit{
  users: string[];

  constructor(private userService:UserServiceService){}
  onSetToInactive(id: number) {
    this.userService.setToInactive(id);
  }

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

- inactive-user-component.ts

```typescript
import { Component, OnInit } from '@angular/core';
import { UserServiceService } from '../user-service.service';

@Component({
  selector: 'app-inactive-users',
  templateUrl: './inactive-users.component.html',
  styleUrls: ['./inactive-users.component.css']
})
export class InactiveUsersComponent implements OnInit{
  users: string[];

  constructor(private userService: UserServiceService) {}

  onSetToActive(id: number) {
    this.userService.setToActive(id);
  }

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

- app-component.ts

```typescript
import { Component } from '@angular/core';
import { UserServiceService } from './user-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserServiceService]
})
export class AppComponent {
  
}
```

{% stackblitz services-demo-app file=src/index.html %}

So this is a simple use case for the usage of service.

{%github Rohithv07/Extra-Material-For-Angular %}