Service
- A class with a focused purpose
- Used for features that:
Are independent from any particular component
Provide shared data or logic across components
Encapsulate external interactions
Building Service
Create the service class
Define the metadata with a decorator
Import what we need
ng g service services/rootservice --flat
Create service under services directory
rootservice.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class RootserviceService { constructor() { } hello() { console.log('HELLO') } }
Injectable decorator : This case is in root, we can consider for example only specific module
testservicecomp.component.ts
import { Component, OnInit } from '@angular/core'; import { RootserviceService } from '../services/rootservice.service' @Component({ selector: 'app-testservicecomp', templateUrl: './testservicecomp.component.html', styleUrls: ['./testservicecomp.component.css'], // providers: [ RootserviceService ] }) export class TestservicecompComponent implements OnInit { constructor(private rootService: RootserviceService) { } ngOnInit(): void { this.rootService.hello(); } }
コメント