Last active
March 23, 2020 12:56
-
-
Save mike1477/4bea1933d29cd8c6483c9d0aacec7c42 to your computer and use it in GitHub Desktop.
Reactive Angular Unique Username Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Import | |
import { HttpClientModule } from "@angular/common/http"; | |
imports: [ | |
..., | |
..., | |
..., | |
HttpClientModule | |
], |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Imports | |
import { HttpClient } from "@angular/common/http"; | |
import { map} from "rxjs/operators"; | |
//This goes into service | |
validateUsernameNotTaken(control: AbstractControl) { | |
return this.checkUsernameNotTaken(control.value).pipe( | |
map(res => { | |
return res ? null : { usernameTaken: true }; | |
}) | |
); | |
} | |
//Fake API call -- You can have this in another service | |
checkUsernameNotTaken(username: string) { | |
return this.http.get("assets/fakedb.json").pipe( | |
map((usernameList: Array<any>) => | |
usernameList.filter(user => user.username === username) | |
), | |
map(users => !users.length) | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"username": "admin" | |
}, | |
{ | |
"username": "superuser" | |
}, | |
{ | |
"username": "user" | |
}, | |
{ | |
"username": "user123" | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment