Angular Services: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 29: Line 29:
}
}
</syntaxhighlight>
</syntaxhighlight>
==Registering the Service===
==Registering the Service==
<syntaxhighlight lang="ts">
<syntaxhighlight lang="ts">
...
...
Line 43: Line 43:
...
...
</syntaxhighlight>
</syntaxhighlight>
==Usage Of Service Code==
==Usage Of Service Code==
<syntaxhighlight lang="ts">
<syntaxhighlight lang="ts">

Revision as of 01:35, 8 September 2020

Introduction

A Service is

  • Reusable piece of functionality
  • Responsibility for sing piece of function

Create a Service if

  • Not required by the view
  • Business logic not used across components
  • Share logic across components

Parts of a Service

  • Class
  • Injectable Decorator
  • Provider, defined in the module as an array

Delivering to a component is simple

Basic Service

Service Code

import {Injectable} from '@angular/core'
@Injectable()
export class LoggerService {

  log(message: string) : void {
    const timeString : string = new Date().toLocaleTimeString()
    console.log(`${message} (${timeString})`)
  }

  error(message: string) :void {
    console.error(`ERROR: ${message}`)
  }
}

Registering the Service

...
import { LoggerService } from './services/logger.service';
...
@NgModule({
  declarations: [
...
  ],
  imports: [
...  ],
  providers: [LoggerService],
...

Usage Of Service Code

class AComponent {
...
   constructor(private loggerService : LoggerService) {}
..
   this.loggerService.log("Whoopee!")