Injecting Service into Angular Async Validator

Eventually, we want to validate somewhat asynchronous inside our reactive forms. Imagine we have an AuthorComponent (a component about ever famous writers) whose form has an author’s name field that needs to check wether a name of an author is already taken. We could solve the problem this manner:

So far, we’re checking our field asynchronous. This is the simplest one approach to accomplish the validation. As far as we can see, there are some downsides:

  • Since our component is stateless we don’t want to provide it a service which communicates with the API. We want to keep our component agnostic rather than smart.
  • Is not cleaner at all handle this sort of validation inside the component itself.

Let’s move the Service and the validation logic from our component to an external validation service. Now is when Angular’s DI comes into play:

Since we want to inject our service inside the validation service, we need to add the Injectable decorator. This lets Angular foresees that our class service might need some dependencies to be injected, in this case, the desired AuthorsService.

Now our component remains stateless (as expected), we’re only providing to it a sort of service (actually it only performs a validation) that knows how to forward a request to our API. Our component itself doesn’t know nothing about any service that interacts with the API, it only talks to a service that handles a validation.