Services and Dependency Injection Flashcards

1
Q

What are services?

A

Services are:

  • Class with focused purpose
  • Used for features that are independent from any particular component
  • Used for providing shared data or logic across components
  • Encapsulate external interactions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How many ways for using service?

A
1 Way: (bad)
Component can create instance of service class and use it. But instance is local to the component and it's difficult to mock the service

2 Way:
Register service with angular. Angular creates a singleton service instance. Angular has a built in injector. It maintains a container of services.
If component needs service, it define the service as a dependency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Dependency injection is

A

A coding pattern in which a class receives the instance of objects it needs (called dependencies) from an external source rather than creating them itself.

In angular the external source is the angular injector.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What to do in order to create a service?

A
  1. Create class

2. Add @Injectable() decorator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How many ways for registering a service

A

Two. Root injector or Component injector.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What Root injector does?

A

Service is available throughout the application.

Recommended for most scenarios

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What Component injector does?

A

Service is only available to that component and its child (nested) components.
Isolates a service used by only one component.
Provides multiple instances of the service.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to register service in root application

A

In @Injectable decorator set {
providedIn: ‘root’
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to register service for specific component

A

In @Component decorator in the component itself add {…
providers: [ProductService]
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How the service is injected?

A

Define it as a depndency.

export class ProductionListComponent {
private _productService;
constructor(productService: ProductService)  {
this._productService = productService;
}
}

A sort cut of this is

constructor(private productService: ProductService)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly