Creating AuthService for injection (@Injectable)
Say AuthService needs to act as a dependency in a component. The first step is to add the @Injectable decorator to show that the class can be injected.
ng generate service auth/auth --skip-tests=true
The next step is to make it available in the DI by providing it. A dependency can be provided in multiple places:
- At the component level
- At the NgModule level
- At the application root level
At the component level
- Using the
providersfield of the@Componentdecorator. - In this case the
AuthServicebecomes available to all instances of this component and other components and directives used in the template. - When you register a provider at the component level, you get a new instance of the service with each new instance of that component.
@Component({
selector: 'app-demo',
template: '...',
providers: [AuthService]
})
class DemoComponent {}
At the NgModule level
- Using the
providersfield of the@NgModuledecorator. - In this scenario, the
AuthServiceis available to all components, directives and pipes declared in thisNgModule. - When you register a provider with a specific
NgModule, the same instance of a service is available to all components in thatNgModule.
@NgModule({
declarations: [],
providers: [AuthService]
})
class DemoModule{}
At the application root level
- Which allows injecting it into other classes in the application.
- This can be done by adding the
providedIn: 'root'field to the@Injectabledecorator. - When you provide the service at the root level, Angular creates a single, shared instance of the
AuthServiceand injects it into any class that asks for it. - Registering the provider in the
@Injectablemetadata also allows Angular to optimize an app by removing the service from the compiled application if it isn’t used, a process known astree-shaking. @Injectable()lets Angular know that a class can be used with the dependency injector.@Injectable()is not strictly required if the class has other Angular decorators on it or does not have any dependencies. What is important is that any class that is going to be injected with Angular is decorated. However, best practice is to decorate injectables with@Injectable(), as it makes more sense to the reader.
@Injectable({
providedIn: 'root'
})
class AuthService {}
- Create a variable viz
isLoggedInwhich we will simply set totruewhenauthenticate()is called. - Also create a method viz
isAuthenticated()which returnsisLoggedInvalue.
@Injectable({
providedIn: 'root'
})
export class AuthService {
private sLoggedIn = false;
isAuthenticated(): boolean {
return this.isLoggedIn;
}
authenticate(): void {
this.isLoggedIn = true;
}
}