In this exercise we'll explore how async validators are implemented in Angular 2. We'll learn how to create a validator that has service dependencies and how it needs to be added to the NG_ASYNC_VALIDATORS
providers.
Email addresses should be unique. We shouldn't have multiple contacts that share the same email address. That's why we want make sure that, when a contact is added, the email address (if applied) isn't already used in an existing contact.
- Add a method
isEmailAvailable(email)
toContactsService
- Use
http.get()
to send a request to{API-ENDPOINT}/check-email?email={EMAIL}
- This endpoint returns
{ error: 'NOT_AVAILABLE' }
- in case the given email address is in use{ msg: 'AVAILABLE' }
- in case the email address is available
- Create a directive using angular-cli called
email-availability-validator
- Add a validator factory function
checkEmailAvailability(contactsService: ContactsService)
tosrc/app/email-availability-validator.ts
. - Return the observable of
ContactsService#isEmailAvailable()
, make sure that it projects/emits the right next value, which is:
null
- if the email address is available or,{ emailTaken: true }
- if the email address is not available
- Inject
ContactsService
intoEmailAvailabilityValidator
- Use
checkEmailAvailability()
as a factory function to store a validator on the class - Implement a method
validate(c: FormControl)
onEmailAvailabilityValidator
which uses the new validator - Change
EmailAvailabilityValidator
's selector to[trmCheckEmailAvailability][ngModel]
. - Add the validator to
NG_ASYNC_VALIDATORS
usingforwardRef
anduseExisting
when configuring the provider - Apply
trmCheckEmailAvailability
directive to email input inContactCreatorComponent
s template - Display an error message accordingly