Angular Services
Creating and injecting services
Service Decorator
@Injectable({ # service decorator
providedIn: 'root' # singleton service
})
export class DataService {
getData() {
return [1, 2, 3];
}
}
Generate Service
ng generate service data # CLI command
ng g s data # shorthand
Constructor Injection
export class AppComponent {
constructor(private dataService: DataService) { # inject service
this.data = dataService.getData();
}
}
HTTP Service
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
this.http.get('api/data').subscribe(data => { });
Provider Scope
providedIn: 'root' # app-wide singleton
providedIn: 'any' # one instance per injector
providers: [DataService] # in component/module