Services are registered as providers at the module level of your application. When we register a service with Angular, it's automatically injected into our module via dependency injection when the service is marked with the @Injectable decorator. After injection, any component or module of our application has access to our shared service through its constructor.
constructor(private injectedService: ServiceName) {}
By setting a value of the service in our AppModule, we can retrieve the same value from the service in our CreatePostFormComponent. This is because the service is effectively a singleton class that is dependency injected into the different parts of our application. This provides a great method of sharing state across the application.
You can also set a service as a provider for a specific component or module. For instance, if I include CurrentUserService in the list of providers for my CreatePostFormComponent, I will actually create a new, totally separate CurrentUserService instance:
...
@Component({
selector: 'app-create-post-form',
templateUrl: './create-post-form.component.html',
styleUrls: ['./create-post-form.component.scss'],
providers: [CurrentUserService]
})
export class CreatePostFormComponent implements OnInit {
model: BlogPost;
user: User;
constructor(private modalService: NgbModal, private currentUserService:
CurrentUserService) {
let user = new User('John', 'Adams', '[email protected]');
this.currentUserService.setUser(user);
}
...
ngOnInit() {
this.user = this.currentUserService.getUser();
}
}
Sometimes, this behavior may be desired for an instance service, such as setting up a web-sockets connection for a component. Usually, this isn't how services are used; make sure that you do not declare your service dependencies more than once if you want to avoid duplicate service instances.