Advice/Opinion: Insert Data to a specific user using Firebase and Angular - javascript

I would really like some advice and opinion I am now currently inserting data from firebase using angular. I can now insert data but the problem is It won't insert inside the child I' am calling.
This is my task-form.component.html:
<form #t="ngForm" (ngSubmit)="add(t.value)">
<div class="form-group">
<label for="taskTechiciansName">Technicians Name</label>
<select ngModel name="taskTechniciansName" id="taskTechniciansName"
class="form-control">
<option value=""></option>
<option *ngFor="let a of techNames$ | async" [value] ="a.$key">
{{ a.name }}
</option>
</select>
</div>
<div class="form-group">
<label for="taskAdd">Address</label>
<input ngModel name="taskAdd" id="taskAdd" type="text" class="form-control">
</div>
<div class="form-group">
<label for="taskDate">Date</label>
<input ngModel name="taskDate" id="taskDate" type="date" class="form-control">
</div>
<div class="form-group">
<label for="taskClass">Class</label>
<input ngModel name="taskClass" id="taskClass" type="text" class="form-control">
</div>
<div class="form-group">
<label for="taskDesc">Description</label>
<input ngModel name="taskDesc" id="taskDesc" type="text" class="form-control">
</div>
<button class="btn btn-primary">Add Task</button>
</form>
here is my code tasks.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';
#Injectable()
export class TaskService {
uid: string;
constructor(private db: AngularFireDatabase,
private af: AngularFireDatabase,
private am: AngularFireAuthModule
) {
}
create(tasks){
return this.db.database.ref('/users/').push({ tasks }).key;
}
}
and this is my database structure:
and this is how the data is being submitted:
task data
I really want to insert the info data into a specific user under tasks child. Your help is greatly appreciated.

The first mistake is a simple typo: you're missing a / in the path:
create(tasks){
return this.db.database.ref('/users/' + this.uid).push({ tasks }).key;
}
The second mistake is just as simple: you never give uid a value, so it's undefined. I'm just not sure how to fix it, since it depends on what you're trying to accomplish.

Related

How can I add a date to an object in Angular?

am sending an put request based on these files.
Venue.ts file
export class Venue {
id: number;
venueName: string;
cityName: string;
emailContact: string;
fighter1: string;
fighter2: string;
dateOfFight: Date;
active: boolean;
}
My Angular Component files:
create-venue.component.html
<h3>Create Event</h3>
<div [hidden]="submitted" style="width: 400px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Venue Name</label>
<input type="text" class="form-control" id="venueName" required [(ngModel)]="venue.venueName" name="venueName">
</div>
<div class="form-group">
<label for="name">City Name</label>
<input type="text" class="form-control" id="cityName" required [(ngModel)]="venue.cityName" name="cityName">
</div>
<div class="form-group">
<label for="name">Email Contact</label>
<input type="text" class="form-control" id="emailContact" required [(ngModel)]="venue.emailContact" name="emailContact">
</div>
<div class="form-group">
<label for="name">Fighter 1 Contact</label>
<input type="text" class="form-control" id="fighter1" required [(ngModel)]="venue.fighter1" name="fighter1">
</div>
<div class="form-group">
<label for="name">Fighter 2 Contact</label>
<input type="text" class="form-control" id="fighter2" required [(ngModel)]="venue.fighter2" name="fighter2">
</div>
<div class="form-group">
<label for="name">Choose a time for your Event:</label>
<input type="datetime-local" class="form-control" id="dateOfFight" min="2021-01-01T00:00" max="2023-06-14T00:00" required [(ngModel)]="venue.dateOfFight" name="dateOfFight">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<div [hidden]="!submitted">
<h4>You submitted successfully!</h4>
<!-- <button class="btn btn-success" (click)="newVenue()">Add</button> -->
</div>
create-venue.component.ts
import { VenueService } from '../venue.service';
import { Venue} from '../venue';
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-create-venue',
templateUrl: './create-venue.component.html',
styleUrls: ['./create-venue.component.css']
})
export class CreateVenueComponent implements OnInit {
venue: Venue = new Venue();
submitted = false;
constructor(private venueService: VenueService,
private router: Router) {}
ngOnInit() {
}
newVenue(): void {
this.submitted = false;
this.venue = new Venue();
}
save() {
this.venueService.createVenue(this.venue)
.subscribe(data => console.log(data), error => console.log(error));
this.venue = new Venue();
this.gotoList();
}
onSubmit() {
this.submitted = true;
this.save();
}
gotoList() {
this.router.navigate(['/venues']);
}
}
My current sent data in chrome:
I am quite new to javascript and angular, maybe this was answered before but I have no idea how to get the input data into the Venue object...
Edit:
This is my header tab:
I
using a string instead of Date type for the dateOfFight property will let you post to the backend without issue.
You can then generate the date with new Date(datestring) on your server if needed. On the front end you can look into date pipes which will help you format the string accordingly.
You also seem to not be capturing any values in your date input. Notice venue.dateOfFight is not even there. Perhaps try logging out your data before posting
You can use a string instead of date type dateOfFight: string;, and before saving, trasform it into a date format with Moment js.
moment(Date.now()).format('YYYY-MM-DD').toString()

type script given error must supply value for formcontrol name id

I have been getting the following error:
ERROR Error: Must supply a value for form control with name: 'id'.
even though i have provided value for the same and here is my typescript code
import { Component, OnInit,Inject } from '#angular/core';
import {MatDialog,MatDialogRef,MAT_DIALOG_DATA} from '#angular/material';
import {FormGroup,FormBuilder,Validators} from '#angular/forms';
import {AdminService} from '../../services/admin.service';
#Component({
selector: 'app-subcategory-modal',
templateUrl: './subcategory-modal.component.html',
styleUrls: ['./subcategory-modal.component.css']
})
export class SubcategoryModalComponent implements OnInit {
subcategoryForm:FormGroup;
category:any;
constructor(public subCategoryDialogref:MatDialogRef<SubcategoryModalComponent>,#Inject(MAT_DIALOG_DATA)public data:string,private formBuilder:FormBuilder,private service:AdminService)
{
this.generateCategory();
}
ngOnInit() {
this.createForm();
this.generateSubcategory(this.data);
}
createForm()
{
this.subcategoryForm=this.formBuilder.group({
id:[null,Validators.required],
subcategoryName:[null,Validators.required],
category:[null,Validators.required]
});
}
generateSubcategory(data)
{
this.service.getSubcategorys(data).subscribe(res=>{
console.log(res.result);
this.subcategoryForm.setValue({
id:res.result.Name
});
},err=>{
});
}
generateCategory()
{
this.service.getCategory().subscribe(res=>{
this.category=res;
});
}
}
and this is my html code :-
<form [formGroup]="subcategoryForm">
<div class="form-group">
<input type="text" class="form-control" formControlName="id"value="" name="id">
</div>
<div class="form-group">
<input type="text" class="form-control" formControlName="subcategoryName" name="subcategoryName" >
</div>
<div class="form-group">
<select class="form-control" name="category" formControlName="category">
<option value="0">-Select-</option>
<option *ngFor="let data of category?.result" value="{{data.id}}">{{data.Name}}</option>
</select>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" name="button">Update</button>
</div>
</form>
can anybody tell me where i'm going wrong? and why this error keeps happening?
Since you want to change only the value of the control id, you should use patchValue instead of setValue method to modify the value of that formControl.
this.subcategoryForm.patchValue({
id:res.result.Name
});
if you want to use setValue method, you can call it from the formControl id :
this.subcategoryForm.controls['id'].setValue(res.result.Name);

How to display recieved form input data to other component in Angular 6?

register.component.html (the form input component)
<div class="card-content">
<form #registerForm="ngForm" (ngSubmit)="onSubmit(Name.value, Email.value)">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="Name"
#Name
ngModel required>
<label for="Name">Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">mail_outline</i>
<input type="text" name="Email"
#Email
ngModel
required
[pattern]="emailPattern">
<label for="Email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<button class="btn-large btn-submit"
type="submit"
[disabled]='!registerForm.valid'>Start</button>
</div>
</div>
</form>
</div>
register.component.ts
........................................................................................
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { QuizService } from '../shared/quiz.service';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
emailPattern = '^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$';
constructor(private route: Router, private quiz: QuizService) { }
user = {
username: '',
email: ''
};
ngOnInit() {
}
onSubmit(name, email) {
this.user.username = name;
this.user.email = email;
this.route.navigate(['quiz']);
console.log(this.user.username, this.user.email); // log works!!
}
}
quiz.component.html (here i want to display the data which user entered in register component)
.........................................................
<div class="row">
<div class="col s6 offset-s3">
<h3>Welcome to quiz</h3>
<b>Your Name is: </b>
<br>
<b>Your Email is: </b>
</div>
</div>
this.route.navigate(['quiz',{username:username,...}])
and in your quiz component receive data
this.route.params.subscribe(params=>{ console.log(params.username)})
don't forget inject the ActivatedRoute in your quiz
constructor(private route:ActivatedRoute)
There are many way to accomplish this but I would suggest looking at NgRX Store, if you want a simpler solution then you can use a service:
#Injectable({
provideIn: ‘root’
})
export class SomeService {
userSubject = new BehaviorSubject<User>({});
user$: Observable<User> = this.userSubject;
}
In your RegisterComponent submit event you will call someService.userSubject.next(this.user); and in your QuizComponent subscribe to someService.user$ to pick up the data

ERROR TypeError: Cannot read property 'title' of undefined

I've been battling with these block of codes for some days, and even when i try initializing it as an object i get errors.
this is my restaurantForm.ts file
import { Component, OnInit } from '#angular/core';
import {RestaurantService} from '../../restaurant.service';
import {ProductService} from '../../product.service';
import {ActivatedRoute, Router} from '#angular/router';
import 'rxjs/add/operator/take';
import {Product} from '../../model/product';
#Component({
selector: 'app-product-form',
templateUrl: './restaurant-form.component.html',
styleUrls: ['./restaurant-form.component.css']
})
export class RestaurantFormComponent implements OnInit {
restaurants$;
id;
product: Product;
constructor(private restaurantService: RestaurantService,
private productService: ProductService,
private route: ActivatedRoute,
private router: Router) {
this.restaurants$ = this.restaurantService.getAll();
this.id = this.route.snapshot.paramMap.get('id');
if (this.id) {
this.productService.get(this.id).take(1).subscribe(p => this.product = p);
}
this.product = new Product();
}
save(product) {
if (this.id) {
this.productService.update(this.id, product);
} else {
this.productService.create(product);
}
this.router.navigate(['/admin/restaurants']);
}
delete() {
if (!confirm('Are you sure you want to delete this product?')) { return ; }
this.productService.delete(this.id);
this.router.navigate(['/admin/restaurants']);
}
ngOnInit() {
}
}
this is my product model
export interface Product {
$key: string;
title: string;
price: number;
restaurant: string;
imageUrl: string;
}
My restaurantForm.html
<div class="container">
<div class="row">
<div class="col-md-6">
<form #f="ngForm" (ngSubmit)="save(f)">
<div class="form-group">
<label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
<div class="alert-danger alert" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
<div class="form-group">
<label for="price">Delivery Price</label>
<div class="input-group">
<span class="input-group-addon">₦</span>
<input #price="ngModel" [(ngModel)]="product.price" name="price" id="price"
type="number" class="form-control" required [min]="0">
</div>
<div class="alert alert-danger" *ngIf="price.touched && price.invalid">
<div *ngIf="price.errors.required">
Delivery Price is required
</div>
<div *ngIf="price.errors.min">
Delivery Price should be 0 or higher.
</div>
</div>
</div>
<div class="form-group">
<label for="restaurant">Restaurant</label>
<select #restaurant="ngModel" [(ngModel)]="product.restaurant" name="restaurant" id="restaurant" class="form-control" required>
<option value=""></option>
<option *ngFor="let r of restaurants$ | async" [value]="r.$key">
{{ r.name }}
</option>
</select>
<div class="alert alert-danger" *ngIf="restaurant.touched && restaurant.invalid">
Please select a restaurant.
</div>
</div>
<div class="form-group">
<label for="imageUrl">Image Url</label>
<input #imageUrl="ngModel" [(ngModel)]="product.imageUrl" name="imageUrl"
id="imageUrl" type="text" class="form-control" required url>
<div class="alert alert-danger" *ngIf="imageUrl.touched && imageUrl.invalid">
<div *ngIf="imageUrl.errors.required">Image Url is required.</div>
<div *ngIf="imageUrl.errors.url">Please enter a valid Url.</div>
</div>
</div>
<button class="btn btn-primary">Save</button>
<button type="button" (click)="delete()" class="btn btn-danger">Delete</button>
</form>
</div>
<div class="col-md-6">
<app-product-card [product]="product" [showActions]="false"></app-product-card>
</div>
</div>
</div>
I get the same errors with price, $key, restaurant and imageUrl.
thanks in advance. Although Ive looked up some solutions saying i should use elvis Operator e.g 'product?.title' this method isnt still working.
Because product is undefined, you need to declare and initialize it with empty object inside the constructor or ngOninit.
EDIT:
You need to have the Product declared in the component as,
const product : Produce = { $key: "", title: "",price:0,restuarant :"" ,imageurl:"" };
When the template get initialized, the product is undefined and it continues until the response return from API. Add a check for the template where you bind the object properties.Do the same for price etc.
<input *ngIf="product.title" #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>

Angular 2 : ERROR TypeError: Cannot read property 'value' of undefined

I am getting the following error on browser console after clicking on Submit button.
In this application I am trying to get information about the Student uploaded code below.
I am unable to find why this error is shown on console.
I have correctly added the formControlName.
Component
import { Component, OnInit, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, AbstractControl } from '#angular/forms';
#Component({
selector: 'app-new-record',
templateUrl: './new-record.component.html',
styleUrls: ['./new-record.component.css']
})
export class NewRecordComponent implements OnInit {
myFormGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myFormGroup = this.formBuilder.group({
name: new FormControl('', Validators.compose([
Validators.required
])),
claz: new FormControl('BCA'),
admissionYear: new FormControl(Validators.compose([Validators.required]))
});
}
ngOnInit() {
}
onSubmit(student) {
console.log('onSubmit called !');
}
}
Template
<form [formGroup]="myFormGroup"
(ngSubmit)="onSubmit(form.value)">
<div class="form-group">
<label for="claz">Class:</label> <select name="claz" formControlName="claz">
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
<option value="M.Sc">M.Sc</option>
<option value="B.Tech">B.Tech</option>
</select>
</div>
<div class="form-group">
<label for="name">Name:</label> <input type="text"
class="form-control" id="name" formControlName="name">
</div>
<div class="form-group">
<label for="admissionYear">Admission Year:</label> <input type="number"
class="form-control" id="admissionYear" formControlName="admissionYear">
</div>
<button type="submit" class="btn btn-default" >Submit</button>
</form>
There is no form defined, instead use myFormGroup which has been defined as formGroup
(ngSubmit)="onSubmit(myFormGroup.value)"

Categories