DEV Community

Cover image for Angular Learning : Practicing Services
Rohith V
Rohith V

Posted on

Angular Learning : Practicing Services

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 :

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);
  }
}
Enter fullscreen mode Exit fullscreen mode
<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>
Enter fullscreen mode Exit fullscreen mode

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

Inactive users code :

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);
  }
}
Enter fullscreen mode Exit fullscreen mode
<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>
Enter fullscreen mode Exit fullscreen mode

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

App component

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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
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();
  }

}
Enter fullscreen mode Exit fullscreen mode
  • counter.service.ts
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() { }
}

Enter fullscreen mode Exit fullscreen mode
  • active-user-component.ts
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;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • inactive-user-component.ts
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;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • app-component.ts
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 {

}
Enter fullscreen mode Exit fullscreen mode

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

GitHub logo Rohithv07 / Extra-Material-For-Angular

Covering some features with more hands on

Extra-Material-For-Angular

Covering some features with more hands on

npm install --save-dev @angular-devkit/build-angular



npm install --save bootstrap@3



Data Binding

Directives

ngFor, ngIf, ngStyle, ngClass

Using renderer

Using HostListener

Using HostBinding

Building structural directive

Services

Logging Service and injecting

Data Service

Injecting Services into Services @Injectable()

Services for Cross - component communication

Routing

Setting and loading routes

Router Links

Navigation Paths and styling active router links

Passing parameters to Routes

Fetch Route parameters, also Reactively

Query paramaters, Fragments

Nested Routes

Redirecting and wildcards

Guards

>> canActivate
>> canActivateChild
>> Fake auth service and canDeactivate

Passing static data to route

Resolve Guard

Location startergies useHash: true

Observables

Undestanding angular observables

Custom observables

Data, Errors, Completion

Operators, Subject

Forms

Template Driven vs Reactive

Template Driven

Creating form

Accessing form with @ViewChild

Validation and validation error

ngModel with two way binding

Grouping form controls

Radio buttons

Resetting forms

Reactive Approach

Creating a form

Syncing HTML…





Top comments (0)