Skip to content
Angular Essentials
GitHub

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 providers field of the @Component decorator.
  • In this case the AuthService becomes 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 providers field of the @NgModule decorator.
  • In this scenario, the AuthService is available to all components, directives and pipes declared in this NgModule.
  • When you register a provider with a specific NgModule, the same instance of a service is available to all components in that NgModule.
@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 @Injectable decorator.
  • When you provide the service at the root level, Angular creates a single, shared instance of the AuthService and injects it into any class that asks for it.
  • Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service from the compiled application if it isn’t used, a process known as tree-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 isLoggedIn which we will simply set to true when authenticate() is called.
  • Also create a method viz isAuthenticated() which returns isLoggedIn value.
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private sLoggedIn = false;
  
  isAuthenticated(): boolean {
    return this.isLoggedIn;
  }
  
  authenticate(): void {
    this.isLoggedIn = true;
  }
}