April 27, 2021, 9:28 p.m.

rockyourcode: Notes on Angular Services (Pluralsight Course)

rockyourcode

Hello šŸ‘‹! Thanks for subscribing.

Notes on Angular Services (Pluralsight Course)

Published on: 2021-04-27

tags: Lab, Angular, TypeScript

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 decorator
  • Provider 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][whatcolor]
  • 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

Thank you for reading my blog posts.

Don't hesitate to reach out via email or Twitter!

You just read issue #9 of rockyourcode. You can also browse the full archives of this newsletter.

Brought to you by Buttondown, the easiest way to start and grow your newsletter.