I’m learning Angular right now – as a React.js fangirl.
Pluralsight offers a free month of learning in April. I’m taking advantage of it.
Here are some notes on the course Angular Services by Brice Wilson.
Angular Services
What and Why?
- reusable piece of (single) functionality shared across components (is it like a React hook? 🤔)
- able to be delivered when and where it is needed
- components should only contain logic for the view, all other logic should be inside services
Creating and Using Services
- service = basically a TypeScript class
@Injectable
decoratorProvider
required
Example Service:
@Injectable
export class SomeService {
// some methods
}
Providing a Service:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
providers: [SomeService],
})
export class AppModule {}
- providers are like recipes
- provider hands service to injector (creates a single instance of the service)
- Angular uses constructor injection
@Injectable({providedIn: 'root'})
is tree-shakable
Dependency Injection
- loosely coupled code, more flexible
- easier to test
- provider: “A dependency provider configures an injector with a DI token, which that injector uses to provide the runtime version of a dependency value.”
- providers are like service recipes
- injectors deliver services & maintain a single instance of each service
- hierarchical injectors
- where to inject? root injector, root AppModule, component-specific services
Asynchronous Services
- can contain synchronous and asynchronous code
- return Observables (part of Rxjs or Promises (ES 2015)
Using Built-In Angular Services
- use the API reference
Summary
The course offers several demos that help you understand how Angular services work. Those are really useful, but I cannot include them here.
Resources
- Angular Services Pluralsight course by Brice Wilson
- What color is your function? by Bob Nystrom