can't add a collection in firebase fireStore - javascript

i'm trying to add a collection in fireBase fireStore so i used this function .collection.(doc).set ; the collection was not created and the console show error register , and despite that i find the new user in authentification in firebase , i hope that i find the good solution . i'm getting crazy
<div class="uk-position-small uk-position-center uk-overlay uk-overlay-default">
<form #f="ngForm" (ngSubmit)="register(f)">
<div class="uk-margin">
<div class="uk-inline">
<span class="uk-form-icon" uk-icon="icon: happy"></span>
<input class="uk-input" type="text" name="firstName" #firstName="ngModel" ngModel required>
<p class="alert alert-danger" *ngIf="firstName.errors?.required && firstName.touched">this input firstName and lastName are required</p>
</div>
</div>
<div class="uk-margin">
<div class="uk-inline">
<textarea class="uk-input" cols="28" rows="10" placeholder="bio" name="bio" #bio="ngModel" ngModel bio required></textarea>
<p class="alert alert-danger" *ngIf="bio.errors?.required && bio.touched">this bio isrequired</p>
</div>
</div>
<div class="uk-margin">
<div class="uk-inline">
<span class="uk-form-icon" uk-icon="mail"></span>
<input class="uk-input" type="text" name="email" #email="ngModel" ngModel email required>
<p class="alert alert-danger" *ngIf="email.errors?.required && email.touched">this input email is required</p>
</div>
</div>
<div class="uk-margin">
<div class="uk-inline">
<span class="uk-form-icon uk-form-icon-flip" uk-icon="icon: lock"></span>
<input class="uk-input" type="password" name="password" #password="ngModel" ngModel password required minlength="8">
<p class="alert alert-danger" *ngIf="password.errors?.required && password.touched">this input password is required</p>
<p class="alert alert-danger" *ngIf="password.errors?.minlength && password.touched">this input password should +8 caratere</p>
</div>
</div>
<div class="uk-margin">
<div class="uk-inline">
<span class="uk-form-icon uk-form-icon-flip" uk-icon="icon: lock"></span>
<input class="uk-input" type="password" name="confirmPassword" #confirmPassword="ngModel" ngModel required minlength="8">
<p class="alert alert-danger" *ngIf="confirmPassword.errors?.required && password.errors?.minlength && confirmPassword.touched">this input confirmpassword is required</p>
<p class="alert alert-danger" *ngIf="password.value!==confirmPassword.value && password.touched">not equal</p>
</div>
</div>
<button type="submit" class="btn btn-success">Register</button>
</form>
</div>
export class RegisterComponent implements OnInit {
constructor(private as:AuthService , private fs:AngularFirestore , private route:Router) { }
ngOnInit(): void {
}
register(f){
// console.log(f.value)
let data=f.value
this.as.signUp(data.email,data.password ).then((user)=>{
this.fs.collection("users").doc(user.user.uid).set({
firstName:data.firstName,
email:data.email,
bio:data.bio,
uid:data.user.user.uid
})
.then(()=>{
console.log('done')
// this.route.navigateByUrl('/home')
})
})
.catch(()=>{
console.log('error register')
})
}
}
#Injectable({
providedIn: 'root'
})
export class AuthService {
user: Observable<firebase.User>;
constructor(private fa:AngularFireAuth) {
this.user=this.fa.user
}
signUp(email,password){
return this.fa.createUserWithEmailAndPassword(email,password)
}
signIn(email,password){
return this.fa.signInWithEmailAndPassword(email,password)
}
}

You're not returning promises in your chain so your code is blowing right by them. If this doesn't solve your issue, then the problem is in your signUp code and you'd have to post that for more help.
register(f){
let data=f.value
this.as.signUp(data.email, data.password).then((user) => {
// You need to return this promise. Right now, your code
// is blowing right by it and immediately calling the next `then`
return this.fs.collection("users").doc(user.user.uid).set({
firstName: data.firstName,
email: data.email,
bio: data.bio,
uid: data.user.user.uid
})
}).then(() => {
// This code block has now waited for the doc to be set
console.log('done')
// this.route.navigateByUrl('/home')
}).catch((error) => {
console.log('error register')
console.log(error)
})
}

Related

Vuelidate - passes validation, but the function does not work after it

I have a form where the user has to enter a field value:
<template>
<div class="authentication-template">
<div class="authentication-template__inner">
<div class="authentication-template__content">
<div class="authentication-template__form-stage">
Этап 1 из 3
</div>
<h2>{{ title }}</h2>
<form #submit.prevent="submitHandler" class="authentication-template__form" action="">
<div class="authentication-template__form-item">
<p>Номер телефона</p>
<input
type="text"
placeholder="+7(921)123-45-67"
maxlength="16"
:class="$v.phone.$error ? 'invalid' : ''"
v-model.trim="phone"
v-imask="phoneNumberMask"
#accept="onAccept"
#complete="onComplete"
#keypress="isNumber"
>
<p v-if="$v.phone.$dirty && !$v.phone.required" class="invalid-feedback">Обязательное поле для заполнения</p>
<p v-if="$v.phone.$dirty && !$v.phone.minLength" class="invalid-feedback">Данное поле должно содержать номер телефона</p>
<p v-if="phone_status == 'error'" class="invalid-feedback">Данный номер телефона уже существует</p>
</div>
<div class="authentication-template__enter">
Еще нет аккаунта? <router-link tag="a" :to="url">Войти</router-link>
</div>
<div class="authentication-template__button">
<button class="button" type="submit">
{{buttonText}}
</button>
</div>
</form>
</div>
</div>
</div>
This is my validations:
validations: {
phone: {required, minLength: minLength(16)},
},
This is my function where does this validation work:
submitHandler(){
this.$v.$touch()
if(!this.$v.$error){
axios.post('http://127.0.0.1:8000/api/v1/check-number/',
{
phone_number: this.phone
}
).then((response) => {
this.phone_status = response.data.status
if(this.phone_status == 'success'){
localStorage.setItem('phone', this.phone)
this.$router.push('/register/2')
}
})
}
}
I enter a value in the field that matches the validation, but after if(!this.$v.$error), my axios request doesn't work, I suspect my if condition is wrong, I'm sitting with this problem for a long time, please can anyone help me?
UPD: if i comment this.$v.$touch() my axios request is work, as I understand it, my form still does not pass validation?

How to clear the form input fileds when user successfully submitted the form in Vue.js?

i have one registration page when user renter some values ,after successfully submission the form need to be clear all the field for that i am using predefined function called reset() inside the script section ,it's not working i am unable to get where did i mistake and one more thing autocomplete="off" is also not working please help me to fix this issue.
Register.vue
<template>
<div class="main">
<div class="container">
<img src="../assets/sideImg.png" alt="notFound" />
<p>Online Book Shopping</p>
<div class="box">
<div class="headings">
<h5 class="signin">Login</h5>
<h5 class="signup">signup</h5>
</div>
<form id="myForm" #submit.prevent="handlesubmit">
<div class="fullname">
<p>FullName</p>
<input type="text" class="namebox" required v-model="FullName" autocomplete="off" pattern="[A-Za-z]{3,12}">
</div>
<div class="username">
<p>EmailID</p>
<input type="email" class="emailbox" required v-model="EmailID" pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="pass">
<p>Password</p>
<input :type="password_type" class="password" v-model="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,}$" required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
</div>
<div class="mobile">
<p>MobileNumber</p>
<input type="tel" class="telephone" v-model="Mobile" pattern="^\d{10}$" required>
</div>
<button class="btn-section" #click="clear();" type="submit">Signup</button>
</form>
</div>
</div>
</div>
</template>
<script>
import service from '../service/User'
export default {
name: 'Register',
data() {
return {
FullName: '',
EmailID: '',
Password: '',
Mobile: '',
password_type: "password",
}
},
methods: {
togglePassword() {
this.password_type = this.password_type === 'password' ? 'text' : 'password'
},
clear(){
document.getElementById("myForm").reset();
},
handlesubmit() {
let userData = {
FullName: this.FullName,
EmailID: this.EmailID,
Password: this.Password,
Mobile: this.Mobile
}
service.userRegister(userData).then(response => {
// console.log("user Details", response);
alert("user registered successfully");
return response;
}).catch(error => {
alert("Invalid Email/Mobile number");
return error;
})
}
}
}
</script>
<style lang="scss" scoped>
#import "#/styles/Register.scss";
</style>
try this:
in your HTML
<form ref="myForm" #submit.prevent="handlesubmit">
in your handlesubmit, after it finishes
this.$refs.myForm.reset();
about autocomplete, found this:
In order to provide autocompletion, user-agents might require elements to:
Have a name and/or id attribute
Be descendants of a element
The form to have a submit button
try adding a name or id to the input.

Vue: login validation not working in my code

I'm creating login validation in Vue.js but the error message is not displaying and it gives me the error:
Property or method "error" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
Any help?
Template:
<template>
<div class="container" width="900">
<div class="row justify-content-center" style="margin-top: 10px;">
<div class="col-5">
<div v-if="error" class="alert alert-danger" role="alert">
{{error}}
</div>
<div class="card" >
<div class="card-text">
<div class="form-group" #keyup.enter="logItIn">
<input class="form-control"
v-model="login.email"
label="Email"
placeholder="Email Address"
required
> <br>
<input class="form-control"
v-model="login.password"
label="Password"
type="password"
placeholder="Password"
required>
</div>
</div>
<button type="button" class="btn btn-secondary" #click='logItIn'>Login</button>
</div>
</div>
</div>
</div>
</template>
Script:
import axios from 'axios'
export default {
data() {
return {
login: {
email:"",
password:"",
error: ""
}
}
},
methods: {
async logItIn() {
try {
axios.post('https://odevin-api.herokuapp.com/login',this.login)
.then(response => {
console.log(response)
let newToken=response.data.response.token;
window.token=newToken;
let user=response.data.response.user; //response
localStorage.setItem('token',newToken);
localStorage.setItem('user',JSON.stringify(user));
window.axios.defaults.params={api_token:newToken}
// Event.$emit('login',user);
this.$router.push('/');
});
} catch(e) {
this.error = 'invalid user name or password';
}
}
}
}
you referenced {{ error }} in your template but in your data object, error is a property of login object. so vue can't find it properly.
either change the usage in your template to {{ login.error }} or define it in your data object like this:
data() {
return {
error: '',
login: {
email: '',
password: '',
},
}
}

Angular - Redirect to Login after register and show a message

I'm working on an Angular and Spring Boot app and I'm very new to Angular. I've made some components, a component for login and one for register, also I've made some validation, etc. Now, what I want to do is when the user registration is successfully the user is redirected to login page and also I want to show a message like this: "Registration Successful! Please Login!" I know how to redirect the user to the login page but I don't know how to show this message for the user.
Register ts
import { Component, OnInit, ViewChild } from '#angular/core';
import { NgForm } from '#angular/forms';
import { User } from '../model/user.model';
import { UserDataService } from '../service/data/user-data.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
invalidRegister = false;
errorMessage = '';
pass1 = '';
pass2 = '';
userName: string;
emailAddress: string;
user: User;
#ViewChild('f') signupForm: NgForm;
constructor(
private userDataService: UserDataService,
private router: Router) { }
ngOnInit() {
}
onSignup(form: NgForm) {
if (this.signupForm.valid === false) {
this.invalidRegister = true;
this.errorMessage = 'You must fill in all the fields!';
} else if (this.pass1 !== this.pass2) {
this.invalidRegister = true;
this.errorMessage = 'The passwords do not match!';
} else {
this.user = new User(this.userName, this.emailAddress, this.pass1);
console.log(this.user);
this.userDataService.addUser(this.user).subscribe(
data => {
console.log(data);
},
error => {
if (error.error.email === "duplicated") {
this.invalidRegister = true;
this.errorMessage = 'The email address you have used is already registered!';
} else if (error.error.username === "duplicated") {
this.invalidRegister = true;
this.errorMessage = 'The username is not available!';
}
},
() => {
this.invalidRegister = false;
this.router.navigate(['login']);
})
}
}
}
Register html
<h1>Register</h1>
<div class="alert alert-warning" *ngIf="invalidRegister">{{ errorMessage }}</div>
<form (ngSubmit)="onSignup()" #f="ngForm">
<div class="form-group row">
<label for="username" class="col-2 col-form-label">Username</label>
<div class="col-6">
<input
type="text"
id="username"
name="username"
ngModel
class="form-control"
required
#username="ngModel"
[(ngModel)]="userName">
<span
class="help-block text-danger"
*ngIf="!username.valid && username.touched">The username field is required!</span>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-2 col-form-label">Email</label>
<div class="col-6">
<input
type="email"
id="email"
name="email"
ngModel
class="form-control"
required
email
#email="ngModel"
[(ngModel)]="emailAddress">
<span
class="help-block text-danger"
*ngIf="!email.valid && email.touched">Please enter a valid email!</span>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-2 col-form-label">Password</label>
<div class="col-6">
<input
type="password"
id="password"
name="password"
ngModel
class="form-control"
required
#password="ngModel"
[(ngModel)]="pass1">
<span
class="help-block text-danger"
*ngIf="!password.valid && password.touched">The password field is required!</span>
</div>
</div>
<div class="form-group row">
<label for="pass" class="col-2 col-form-label">Confirm Password</label>
<div class="col-6">
<input
type="password"
id="pass"
name="pass"
ngModel
class="form-control"
required
#pass="ngModel"
[(ngModel)]="pass2">
<span
class="help-block text-danger"
*ngIf="!pass.valid && pass.touched">Please confirm your password!</span>
</div>
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
Login ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { BasicAuthenticationService } from '../service/basic-authentication.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
username = '';
password = '';
errorMessage = 'Invalid Credentials';
invalidLogin = false;
constructor(
private router: Router,
private basicAuthenticationService: BasicAuthenticationService) { }
ngOnInit() {
}
handleBasicAuthLogin() {
this.basicAuthenticationService.executeAuthenticationService(this.username, this.password)
.subscribe(
data => {
console.log(data);
this.router.navigate(['welcome', this.username]);
this.invalidLogin = false;
},
error => {
console.log(error);
this.invalidLogin = true;
}
);
}
Login html
<h1>Login</h1>
<div class="container">
<div class="alert alert-warning" *ngIf='invalidLogin'>{{ errorMessage }}</div>
<div>
User Name: <input type="text" name="username" [(ngModel)]="username" >
Password: <input type="password" name="password" [(ngModel)]="password">
<button (click)="handleBasicAuthLogin()" class="btn btn-success">Login</button>
</div>
</div>
When the registration is successful, you can add query params to the route and navigate to login
this.router.navigate(['login'], {queryParams: { registered: 'true' } });
Url will look like this: https://foobar.com/login?registered=true
In login.ts
infoMessage = '';
ngOnInit() {
this.route.queryParams
.subscribe(params => {
if(params.registered !== undefined && params.registered === 'true') {
infoMessage = 'Registration Successful! Please Login!';
}
});
}
And add this kind of line in login.html
<span *ngIf="infoMessage.length > 0">{{ infoMessage }}</span>

How to bind error data "Invalid username and password" and " Username already exists" in AngularJS

In my response its showing a "Invalid username or password" message that is coming from server(node) if I enter invalid fields. But I don't know how to populate that in my template. I tried many examples but none of them worked for me. How to write services and controllers for it? TIA
Template:
<div ng-if="messages.error" role="alert" class="alert alert-danger">
<div ng-repeat="error in messages.error">{{error.msg}}</div>
</div>
<form name="frmRegister" ng-submit="login()" role="form">
<legend>Log In</legend>
<div class="form-group" ng-class="{ 'has-error': frmRegister.email.$dirty && frmRegister.email.$error.required }">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Email" class="form-control" ng-model="user.email" required>
<span ng-show="frmRegister.email.$dirty && frmRegister.email.$error.required" class="help-block">Email is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': frmRegister.password.$dirty && frmRegister.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Password" class="form-control" ng-model="user.password"
required>
<span ng-show="frmRegister.password.$dirty && frmRegister.password.$error.required" class="help-block">Password is required</span>
</div>
<button type="submit" id="submit" class="btn btn-success">Log in</button>
</form>
Controller:
angular.module('MyApp')
.controller('LoginCtrl', function($scope,$rootScope, $location, $auth, toastr, $http) {
$scope.login = function() {
$http ({
method : 'POST',
url: 'http://localhost:3000/onio/v1/login',
data : $scope.user
});
$auth.login($scope.user)
.then(function() {
toastr.success('You have successfully signed in!');
$location.path('/');
})
.catch(function(error) {
toastr.error(error.data.message, error.status);
});
};
$scope.authenticate = function(provider) {
$auth.authenticate(provider)
.then(function() {
$rootScope.currentUser = response.data.user;
toastr.success('You have successfully signed in with ' + provider + '!');
$location.path('/');
})
.catch(function(error) {
if (error.message) {
// Satellizer promise reject error.
toastr.error(error.message);
} else if (error.data) {
// HTTP response error from server
toastr.error(error.data.message, error.status);
} else {
toastr.error(error);
}
});
};
});
You need to bind the error data from the server to your scope so it can be used in your template. In your catch block try:
.catch(function(error) {
$scope.error_message = error.data.message
toastr.error(error.data.message, error.status);
});
Then in the html, you can bind that error message wherever you need it:
<div ng-if="error_message" role="alert" class="alert alert-danger">
<div>{{error_message}}</div>
</div>

Categories

Resources