I'm trying to implement a form validation that checks on Firebase if a username exists. If it doesn't, then the form becomes invalid.
The form validation works fine when I mock the data using an Observable. However, it doesn't work when I fetch the data from Firebase.
This works:
fromMockData(username: string): Observable<Usernames> {
return username === 'demo' ? Observable.of({ uid: 'test' }) : Observable.of(null);
}
This one doesn't:
fromFirebase(username: string): Observable<Usernames> {
return this.afs.doc(`usernames/${username}`).valueChanges();
}
I'm accessing both services from a validation service:
fromFirebase(input: FormControl): Observable<{[key: string]: any}> {
return this.service.fromFirebase(input.value).pipe(
map(user => user ? { invalidUsername: `#${input.value} already exists` } : null),
);
}
Any ideas why it doesn't work when fetching the data from Firebase?
PS. I can see the correct value when logging user into the console - even when using Firebase. However, it's not returning the proper value to the form's errors properties (it only works in the first case: creating an Observable with mock data).
This is my form, btw:
this.form = this.fb.group({
username: ['', [], [this.validator.fromFirebase.bind(this.validator)]],
});
Demo
Because Firebase returns a streaming of data, I need to use the first operator so that only the first item is emitted:
fromFirebase(input: FormControl): Observable<{[key: string]: any}> {
return this.service.fromFirebase(input.value).pipe(
first(),
map(user => user ? { invalidUsername: `#${input.value} already exists` } : null),
);
}
Related
Please, I am having issues working with some async data on angular which comes from my API. I’ve spent some time trying to figure out how to scale through, but I still get stuck.
Scenario
When on edit mode of a patient form, I need to call my centre service to get all available centres from db. When the data is returned, I need to process the data to check which centres a patient belong to, then use this on the html. But I see that the component renders before data is received. This is because, when I click save button to check the data, I see the data there. But in the method where I need to write some logic, when I try to inspect the data returned from the API, it remains undefined.
NB: I can’t use a resolver in this case because, I’m not using a router link to navigate to the page.
I’ve tried to use an async pipe to conditionally check and render the html only if I receive the data which was one solution that worked for someone else. But this seem not to work in my case as i still get undefined on the variable which is inside a method, and where I need to process the data returned before showing my component/html.
Goal
The goal is to first get all centres first before initializing the reactive form, so that i can handle the data on the getPatientCentres() method. I intend to use the data gotten from the API to pre-populate an array when creating the form.
Done other steps and research but the solution doesn’t seem to solve my case.
Any help or logic on how to proceed would be highly appreciated.
Here is my TS code
export class Patient2Component implements OnInit {
formTitle: string;
patientForm: FormGroup;
centreList: ICentre[] = [];
loadedData: boolean = false;
patient: IPatient;
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private centreService: CentreService,
) { }
ngOnInit() {
this.getCentres();
this.initCentreForm();
this.checkParamsForEditAction();
}
initCentreForm() {
this.patientForm = this.fb.group({
id: [null],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
centres: [this.centreList]
});
}
getCentres() {
this.centreService.getCentres().subscribe(res => {
this.centreList = res;
// this.loadedData = true;
});
}
checkParamsForEditAction() {
this.activatedRoute.data.subscribe(data => {
this.patient = data['patient'];
if (this.patient) {
this.formTitle = 'Edit Patient';
this.getPatientCentres(this.patient);
this.assignValuesToControl(this.patient);
}
});
}
assignValuesToControl(patient: IPatient) {
this.patientForm.patchValue({
id: patient.id,
firstName: patient.firstName || '',
lastName: patient.lastName || '',
});
}
getPatientCentres(patient: IPatient) {
const patientCentres = patient.patientCentres;
/**Here, the centreList is undefined since data has not returned yet
* And i need this data for processing.
*/
console.log(this.centreList);
}
save() {
/**Here, i can see the data */
console.log(this.centreList);
}
Try this
in ngOnInit
ngOnInit() {
this.initCentreForm();
this.getCentres(this.checkParamsForEditAction);
}
getCenters Method
getCentres(callBack?) {
this.centreService.getCentres().subscribe(res => {
this.centreList = res;
// this.loadedData = true;
if(callBack) {
callBack();
}
});
}
you can also use forkJoin, or async await
getCentres(callBack?) {
this.centreService.getCentres().subscribe(res => {
this.centreList = res;
// this.loadedData = true;
//Now call your function directly
this.checkParamsForEditAction();
});
}
Call your function after the get centers is loaded
Order of calling
this.initCentreForm();
this.getCentres();
I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :
500: Need more information
I wonder if it's possible to know which params are missing when I return the error code.
This is for a new API made in NodeJS
Here are the params that I want to retrieve from the front ( made in ReactJS )
let body = {
agentDutyCode: "STRING",
RatePlanCode: params.rateCode,
RoomCode: params.roomCode,
AmountAfterTax: params.amountTax,
Start: params.fromDate,
End: params.toDate,
CardCode: params.cardCode,
CardNumber: params.cardNumber,
ExpireDate: params.expireDate,
SeriesCode: params.cvv,
CardHolderName: params.nameCard,
ChainCode: params.chainCode,
HotelCode: params.hotelCode,
RoomQuantities: params.roomQuantities,
GuestQuantitie: params.numberGuest,
GuestPerRoom: params.guestPerRoom,
LastName: params.lastName,
FirstName: params.firstName,
PhoneNumber: params.phoneNumber,
email: params.email,
FVL_SUBUNIT_7: params.walletAddress
}
And this is my promise :
cdsJson.bookResource(req.body)
.then((response) => {
if (response !== null) {
res.response = {
...response
}
} if (response.hotel.length === 0) {
res.respStatus = 500
res.response = {
sendMsg: "Need more informations"
}
next('route')
}
return response
})
If the request succeeds I got a reservation ID otherwise I got :
Error 500: Need more information
Read the documentation or the source code.
Seriously. If the API response doesn't tell you in the error message, then there is no way to know what parameters it expects programmatically.
try it for a for ... in loop like this:
cdsJson.bookResource(req.body)
.then((response) => {
if (response !== null) {
res.response = {
...response
}
} if (response.hotel.length === 0) {
res.respStatus = 500
let errorStr = "Need more informations"
for(var key in req.body) { // Get all parameters that are not set
if(objects[key] == undefined)
errorStr += "\nParameter ["+key+"] is missing!"
}
res.response = {
sendMsg: errorStr
}
next('route')
}
return response
})
You're trying to do server side validation. In Node a good approach would be to define a JSON Schema for the expected parameters and then in your route handler validate the data sent in the request with a JSON Schema validator. This would help you work out whether a request was valid and help you generate error messages automatically. As a rule it's much better (i.e. simpler and more maintainable) to use tools that enable you to declaratively declare your validation (via a schema) than imperatively write code to manually validate objects.
JSON Schema spec https://json-schema.org/
A validator https://github.com/epoberezkin/ajv
I am building a reactive angular form and I'm trying to find a way to trigger all validators on submit. If the validor is a sync one, it'd be ok, as I can get the status of it inline. Otherwise, if the validator is an async one and it was not triggered yet, the form on ngSubmit method would be in pending status. I've tried to register a subscribe for the form statusChange property, but it's not triggered when I call for validation manualy with markAsTouched function.
Here's some snippets:
//initialization of form and watching for statusChanges
ngOnInit() {
this.ctrlForm = new FormGroup({
'nome': new FormControl('', Validators.required),
'razao_social': new FormControl('', [], CustomValidators.uniqueName),
'cnpj': new FormControl('', CustomValidators.cnpj),
});
this.ctrlForm.statusChanges.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
)
}
//called on ngSubmit
register(ctrlForm: NgForm) {
Forms.validateAllFormFields(this.ctrlForm);
console.log(ctrlForm.pending);
//above will be true if the async validator
//CustomValidators.uniqueName was not called during form fill.
}
//iterates on controls and call markAsTouched for validation,
//which doesn't fire statusChanges
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
Any ideas on how can I ensure that the async validator was executed so I can continue with the register logic having all validators triggered and completed?
Angular doesn't wait for async validators to complete before firing ngSubmit. So the form may be invalid if the validators have not resolved.
Using a Subject to emit form submissions, you can switchMap to form.statusChange and filter the results.
Begin with a startWith to ensure there's no hanging emission, in the case the form is valid at the time of submission.
Filtering by PENDING waits for this status to change, and take(1) makes sure the stream is completed on the first emission after pending: VALID or INVALID.
//
// <form (ngSubmit)="formSubmitSubject$.next()">
this.formSubmitSubject$ = new Subject();
this.formSubmitSubject$
.pipe(
tap(() => this.form.markAsDirty()),
switchMap(() =>
this.form.statusChanges.pipe(
startWith(this.form.status),
filter(status => status !== 'PENDING'),
take(1)
)
),
filter(status => status === 'VALID')
)
.subscribe(validationSuccessful => this.submitForm());
You can also add a tap that triggers the side effect of settings the form as dirty.
Use formGroup.statusChanges to wait for asyncValidators to finish before proceed to submitting form. If the asyncValidators have no error, proceed to submit. On the other hand, if it fails, don't submit. Your form should already handle failed validators. Remember to unsubscribe the subscription if you no longer need it.
if (this.formGroup.pending) {
let sub = this.formGroup.statusChanges.subscribe((res) => {
if (this.formGroup.valid) {
this.submit();
}
sub.unsubscribe();
});
} else {
this.submit();
}
markAsTouched will not fire the validation, use markAsDirty instead, then your custom validator will fire. So change...
control.markAsTouched({ onlySelf: true });
to
control.markAsDirty({ onlySelf: true });
Also if you are using v 5, you can use the optional updateOn: 'submit', which will not update values (and therefore not validations) until form is submitted. For that, make the following changes:
this.ctrlForm = new FormGroup({
'nome': new FormControl('', Validators.required),
'razao_social': new FormControl('', [], CustomValidators.uniqueName),
'cnpj': new FormControl('', CustomValidators.cnpj),
}, { updateOn: 'submit' }); // add this!
With this, it means that you do not need to call this.validateAllFormFields(control) anymore, which I assume switches some boolean flag and checks validation or something like that.
Here is a sample of a form, which always returns an error after submitting form:
https://stackblitz.com/edit/angular-rjnfbv?file=app/app.component.ts
I just implemented a version of this in my app which manually invokes every controls synchronous and asynchronous validators and returns a boolean indicating whether or not all validation passed:
checkIfFormPassesValidation(formGroup: FormGroup) {
const syncValidationErrors = Object.keys(formGroup.controls).map(c => {
const control = formGroup.controls[c];
return !control.validator ? null : control.validator(control);
}).filter(errors => !!errors);
return combineLatest(Object.keys(formGroup.controls).map(c => {
const control = formGroup.controls[c];
return !control.asyncValidator ? of(null) : control.asyncValidator(control)
})).pipe(
map(asyncValidationErrors => {
const hasErrors = [...syncValidationErrors, ...asyncValidationErrors.filter(errors => !!errors)].length;
if (hasErrors) { // ensure errors display in UI...
Object.keys(formGroup.controls).forEach(key => {
formGroup.controls[key].markAsTouched();
formGroup.controls[key].updateValueAndValidity();
})
}
return !hasErrors;
})).toPromise();
}
Usage:
onSubmitForm() {
checkIfFormPassesValidation(this.formGroup)
.then(valid => {
if (valid) {
// proceed
}
});
}
If I got a form (reactive form) with the class FormGroup, I use AbstractControl/Property/valid to check if the form is valid before I continue to send it to a server.
The async validator I use, must return => Promise<ValidationErrors | null> before the form gets valid again after a change to a form field. It would be weird if Google didn't design it like this... But they did!
Reactive Form Validation
There is also a solution implemented as a directive in this issue in angular https://github.com/angular/angular/issues/31021
I am trying to implement a search function where a user can return other users by passing a username through a component. I followed the ember guides and have the following code to do so in my routes file:
import Ember from 'ember';
export default Ember.Route.extend({
flashMessages: Ember.inject.service(),
actions: {
searchAccount (params) {
// let accounts = this.get('store').peekAll('account');
// let account = accounts.filterBy('user_name', params.userName);
// console.log(account);
this.get('store').peekAll('account')
.then((accounts) => {
return accounts.filterBy('user_name', params.userName);
})
.then((account) => {
console.log(account);
this.get('flashMessages')
.success('account retrieved');
})
.catch(() => {
this.get('flashMessages')
.danger('There was a problem. Please try again.');
});
}
}
});
This code, however, throws me the following error:
"You cannot pass '[object Object]' as id to the store's find method"
I think that this implementation of the .find method is no longer valid, and I need to go about returning the object in a different manner. How would I go about doing this?
You can't do .then for filterBy.
You can't do .then for peekAll. because both will not return the Promise.
Calling asynchronous code and inside the searchAccount and returning the result doesn't make much sense here. since searchAccount will return quickly before completion of async code.
this.get('store').findAll('account',{reload:true}).then((accounts) =>{
if(accounts.findBy('user_name', params.userName)){
// show exists message
} else {
//show does not exist message
}
});
the above code will contact the server, and get all the result and then do findBy for the filtering. so filtering is done in client side. instead of this you can do query,
this.store.query('account', { filter: { user_name: params.userName } }).then(accounts =>{
//you can check with length accounts.length>0
//or you accounts.get('firstObject').get('user_name') === params.userName
//show success message appropriately.
});
DS.Store#find is not a valid method in modern versions of Ember Data. If the users are already in the store, you can peek and filter them:
this.store.peekAll('account').filterBy('user_name', params.userName);
Otherwise, you'll need to use the same approach you used in your earlier question, and query them (assuming your backend supports filtering):
this.store.query('account', { filter: { user_name: params.userName } });