How to Login with json-server in Angular 5? - json

I'm newbie in Angular. I am stuck into login section. What to code in loginUser() using json? Please help me.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule} from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { CollapseModule } from 'ngx-bootstrap';
import { HomeComponent } from './component/home/home.component';
import { AboutComponent } from './component/about/about.component';
import { ContactComponent } from './component/contact/contact.component';
import { RegisterComponent } from './component/register/register.component';
import { LoginComponent } from './component/login/login.component';
const appRoutes: Routes = [
{path:'', component:HomeComponent},
{path:'about', component:AboutComponent},
{path:'contact', component:ContactComponent},
{path:'register', component:RegisterComponent},
{path:'login', component:LoginComponent},
];
#NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent,
RegisterComponent,
LoginComponent
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot(appRoutes),
CollapseModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
register.component.html
<div class="col-md-6 col-md-offset-3">
<h2>Register</h2>
<form #userData = "ngForm" (ngSubmit) = "addUser(userData.value)">
<div class="form-group" >
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" [(ngModel)]="firstName" required />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" name="lastName" [(ngModel)]="lastName" required />
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" [(ngModel)]="username" required />
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" [(ngModel)]="email" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="password" required />
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
<a routerLink="/login" class="btn btn-primary">Login</a>
<a routerLink="/" class="btn btn-link">Cancel</a>
</div>
</form>
</div>
register.component.ts
import { Component, OnInit } from '#angular/core';
import { Http, Response, Headers } from '#angular/http';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
constructor(private http: Http, private router: Router) { }
userAddString: string = "User Registered Successfully";
userObj:object = {};
addUser(user){
this.userObj = {
"fname": user.firstName,
"lname": user.lastName,
"email": user.email,
"username": user.username,
"password": user.password
};
this.http.get("http://localhost:4201/users/", this.userObj).subscribe((Response) => {
console.log(this.userObj);
this.router.navigate(['/login']);
})
}
ngOnInit() {
console.log('Register Component Running...');
}
}
login.component.html
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form #loginData = "ngForm" (ngSubmit) = "loginUser(loginData.value)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" required />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
<!-- <input type="submit" value="Login" /> -->
<a routerLink="/register" class="btn btn-primary">Sign Up</a>
<a routerLink="/" class="btn btn-link">Cancel</a>
</div>
</form>
I want to logged in and redirect to user profile using json already created.
login.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Http, Response, Headers } from '#angular/http';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router, private http: Http) { }
ngOnInit() {
console.log('login Component Running...');
}
loginUser(){
}
How to Login with json-server in Angular 5?

Logging in application, with proper Authentication, is critical part of any application. You can make use of many ways available to perform Authentication in Angular way. One of the simplest way is to go with JWT based Auth0 authentication.
For this, you will have to create a back-end server where this authentication if performed.
you can make use of following example as your refrence:
//Get Username and Passwerd from the HTML component, as entered by the user
loginUser(){
this.http.post('http://localhost:3001/user/authenticate', { username: username, password: password })
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
});
}
For the server side authentication, you have to create a different module named 'server', where you can make use of index.js as below:
var express = require('express');
var app = express();
var jwt = require('express-jwt');
var cors = require('cors');
var jwt1 = require('jsonwebtoken');
var Q = require('q');
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cors());
app.post('/user/authenticate',function(req, res){
console.log(req.body);
var obj = req.body;
var user= obj.username;
var pwd= obj.password;
var deferred = Q.defer();
if(user=='admin' && pwd== 'admin')
{
// authentication successful
deferred.resolve({
_id: 1001,
username: 'admin',
firstName: 'Admin',
lastName: '----',
password: 'admin',
token: jwt1.sign({ sub: 1001 }, 'admin')})
}else{
// authentication failed
deferred.resolve();
}
deferred.promise.then(function (user) {
if (user) {
// authentication successful
res.send(user);
} else {
// authentication failed
res.status(400).send('Username or password is incorrect');
}}) .catch(function (err) {
res.status(400).send(err);
});
});
app.listen(3001);
console.log("Listening on http://localhost:3001");
You can make use of following package.json:
{
"name": "angular-js-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rahulk",
"license": "ISC",
"dependencies": {
"#angular/core": "^4.4.6",
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"express-jwt": "^5.3.0",
"jsonwebtoken": "^8.1.0",
"lodash": "^4.17.4",
"q": "^1.5.1"
},
"devDependencies": {
"#angular/cli": "^1.4.9"
}
}
Your server folder will look like follows:
Once done with this, execute server from terminal as: node index.js

Related

zone-evergreen.js:2952 POST http://127.0.0.1:8000/api/users/ 404 (Not Found)

I am new to Angular and Django. I am trying to create a website that uses Angular as a front-end and Django as a back-end, where Angular sends an Object (which contains name, email & query) to Django using DjangoRestFramework. (posting data from Angular to Django)
CONTACT FORM SS
enter image description here
HERE IS MY ANGULAR FILES
contact.component.html:
<form #userForm="ngForm" (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="col-sm">
<ul>
<li>Contact No:</li> +91 8425007230 <br><br>
<li>Email:</li> sanketsbhosale#outlook.com / sanketsbhosale2016#gmail.com
</ul>
</div>
<div class="col-sm s1">
<input type="text" required #name="ngModel" [class.is-invalid]="name.invalid && name.touched" class="form-control" placeholder="Name" name="name" [(ngModel)]=userModel.username>
<small class="text text-danger" [class.d-none]="name.valid || name.untouched">Name is Required!</small> <br> <br>
<input type="text" required #email="ngModel" [class.is-invalid]="name.invalid && email.touched" class="form-control" placeholder="Email" name="email" [(ngModel)]=userModel.email> <br> <br>
<small class="text text-danger" [class.d-none]="email.valid || email.untouched">Email is Required!</small>
</div>
<div class="col-sm s1">
<textarea class="form-control" required #query="ngModel" [class.is-invalid]="query.invalid && query.touched" placeholder="Tell me your Query" style="height: 118px;" name="query" [(ngModel)]=userModel.last_name></textarea>
<small class="text text-danger" [class.d-none]="query.valid || query.untouched">Please Provide Query!</small>
</div>
</div>
<button [disabled]="userForm.form.invalid" class="btn btn-primary" style="margin-left : 330px;">Send Message</button>
</form>
contact.component.ts:
import { Component, OnInit } from '#angular/core';
import { PostDataService } from '../post-data.service';
#Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
providers:[PostDataService]
})
export class ContactComponent implements OnInit {
userModel;
constructor(private _dataPost: PostDataService) { }
onSubmit(){
this._dataPost.enroll(this.userModel)
.subscribe(
response => {
alert("Data is Submitted")
},
error => alert("Error in submitting data"),
);
}
ngOnInit() {
this.userModel = {
username : '',
email: '',
last_name: '',
}
}
}
post-data.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PostDataService {
_url = 'http://127.0.0.1:8000/api/users/';
constructor(private http: HttpClient) { }
enroll(userData): Observable<any> {
return this.http.post(this._url, userData)
}
}
HERE IS MY DJANGO FILES
settings.py
# here only necessary code I have posted
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:4200",
]
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'last_name']
URLs.py(root URL file)
From Django.contrib import admin
from Django.URLs import include a path
from rest_framework import routers
From sample.API import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from sample.api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer

My CRUD Application In Angular Using API is not working as a Single Page Application(SPA) while updating

I have performed the CRUD Application In Angular Using API and it is working fine but the problem is that when I am updating the values it is not showing the updated value instantly, I have to reload the page.
This is my app.component.ts:
import {Component} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {Employee} from './employees';
import {EditComponent} from './edit/edit.component';
import {AppService} from './app.service';
import {Router} from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService]
})
export class AppComponent {
form:any = {}
msg: string = null;
employees: Employee[];
constructor(
public http: HttpClient,private appService:AppService,private router: Router
){}
onSubmit(){
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
this.http.post('http://127.0.0.1:8000/api/employee',this.form,httpOptions)
.subscribe(employee=>{
employee = employee;
this.msg = 'Updated successfully!';
this.getEmployee();
});
}
ngOnInit() {
this.getEmployee();
}
getEmployee():void{
this.appService.getEmployees().subscribe(employees=>(this.employees = employees))
}
delete(employee: Employee): void{
if(confirm("Are you sure want to delete ?")) {
console.log("user details delete successfully!!");
this.employees = this.employees.filter(h =>h !== employee);
this.appService.deleteEmployees(employee.id).subscribe();
this.msg = 'Employee details delete successfully!!';
}else{
}
}
public editComponent: boolean = false;
loadMyChildComponent($id)
{
this.editComponent = true;
this.appService.setCurrentId($id);
}
}
This is my edit.component.ts:
import {Component, OnInit, Input} from '#angular/core';
import {AppService} from '../app.service';
import {Employee} from '../employees';
import {Router} from '#angular/router';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {NgForm} from '#angular/forms';
import {Observable} from 'rxjs';
import { ActivatedRoute } from '#angular/router';
import {FormBuilder, FormGroup, Validators} from "#angular/forms";
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
#Input() employee: Employee[];
form:any = {}
msg: string = null;
constructor(public http: HttpClient,private appService:AppService,private router: Router,private route: ActivatedRoute) { }
ngOnInit(){
this.editEmployees();
}
editEmployees():void{
const id = this.appService.getCurrentId();
this.appService.editEmployees(id).subscribe(employee => {
this.employee = employee;
this.editEmployees();
});
}
onformSubmit()
{
this.appService.updateEmployees(this.employee).subscribe(employee=>{
this.employee = employee;
this.msg = 'Updated successfully!';
});
}
}
This is my employees.ts:
export interface Employee{
id: number;
username:string;
email:string;
mobile:string;
password:string;
}
This is my app.component.html: where I am showing the values and edit button.
<table class="table">
<tr>
<th>Id</th>
<th>User Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr *ngFor="let employee of employees">
<td>{{employee.id}}</td>
<td>{{employee.username}}</td>
<td>{{employee.email}}</td>
<td>{{employee.mobile}}</td>
<td><button (click)="loadMyChildComponent(employee.id);" class="btn btn-primary" [routerLink]="['/edit',employee.id]">Edit</button></td>
<td><button class="btn btn-danger" (click)="delete(employee)" > Delete</button></td>
</table>
This is my edit.component.html:
<div class="mydiv22">
<p class="msg_success">{{ msg }}</p>
<h2>Update Form</h2>
<div class="row">
<div class="col-md-12">
<form name="form" (ngSubmit)="f.form.valid && onformSubmit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control" name="username" [(ngModel)]="this.employee.username" #username="ngModel"
[ngClass]="{'is-invalid': f.submitted && username.invalid}" required id="username"/>
<div *ngIf="f.submitted && username.invalid" class="invalid-feedback">
<div *ngIf="username.errors.required">>> required</div>
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" [(ngModel)]="this.employee.email" #email="ngModel" [ngClass]="{'is-invalid': f.submitted && email.invalid}"
required email placeholder="Enter your email address" id="email"/>
<div *ngIf="f.submitted && email.invalid" class="invalid-feedback">
<div *ngIf="email.errors.required">>> required</div>
<div *ngIf="email.errors.email">>> must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label for="mobile">Mobile</label>
<input type="number" class="form-control" name="mobile" [(ngModel)]="this.employee.mobile" #mobile="ngModel"
[ngClass]="{'is-invalid': f.submitted && mobile.invalid}" required placeholder="Enter your mobile" pattern="[789][0-9]{9}" minlength="10" id="mobile"/>
<div *ngIf="f.submitted && mobile.invalid" class="invalid-feedback">
<div *ngIf="mobile.errors.required">>> required</div>
<div *ngIf="mobile.errors.pattern">>>Please enter a valid mobile number</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="this.employee.password" #password="ngModel"
[ngClass]="{'is-invalid':f.submitted && password.invalid}" required minlength="6" placeholder="Create your password" id="password"/>
<div *ngIf="f.submitted && password.invalid" class="invalid-feedback">
<div *ngIf="password.errors.required">>> required</div>
<div *ngIf="password.errors.minlength">>> must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<button routerLink="/edit" class="btn btn-success">Update</button>
</div>
</form>
</div>
</div>
</div>
The flow is that: when i click the edit button in app.component.html, It will take the id and go to app.component.ts. From app.component.ts, it will go to app.service.ts where it will fetch the values from the API using particular Id. From the app.service.ts, it will pass the values to the edit.component.ts and using edit.component.ts, it will pass the values to edit.component.html.
It is performing every thing fine like when adding the value it is showing instantly, I don't have to reload the page but while updating the values we have to reload the page, it is not showing instantly like SPA.
I want to show the updated values instantly without updating the page. Any help is much appreciated.
You have three components in same page, it is something about component interactions.
Add Output event property in to EditComponent, emit an event after editing of employee , like this:
import { Output, EventEmitter } from '#angular/core'
export class EditComponent {
#Output() updated = new EventEmitter<Employee>();
onFormSubmit() {
this.appService.updateEmployees(this.employee).subscribe(employee=>{
this.employee = employee;
this.msg = 'Updated successfully!';
// fire an updated event after edit employee.
this.updated.emit(employee)
});
}
}
Then, subscribe to the event in app.component.html, like this:
<app-edit (updated)="onUpdated()"></app-edit>
And then, call getEmployee in onUpdated method to reload the employees list , like this:
export class AppComponent {
onUpdated() {
this.getEmployee();
}
}
For more, please refer to https://angular.io/guide/component-interaction
You can add the similar logic to RegisterComponent to get a reload.

How to post an object to an array in a json using Angular 6

So I'm testing Angular 6 functionality out for fun to learn it and running a json-server to load a db.json to a localhost server to acquire via service calls which you can see here
{
"customers": {
"testingTitle": "Testing Title",
"trainData":[
{
"id": 1,
"name": "Test Name 1",
"email": "customer001#email.com",
"tel": "0526252525"
},
{
"id": 2,
"name": "Test Name 2",
"email": "customer002#email.com",
"tel": "0527252525"
},
{
"id": 3,
"name": "Customer003",
"email": "customer003#email.com",
"tel": "0528252525"
},
{
"id": 4,
"name": "123",
"email": "123",
"tel": "123"
}
]
}
I have a test.service.ts as followed which picks up the service:
import { Injectable } from '#angular/core';
import {HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders, HttpParams} from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
import { catchError, map } from 'rxjs/operators';
import 'rxjs/add/observable/throw';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
class Test {
testingTitle: string;
trainData:[
{
id : number;
name: string;
email: string;
tel: string;
}
];
}
#Injectable({providedIn: 'root'})
export class TestService {
constructor(private http: HttpClient) {}
public getAllTests(): Observable<Test[]>{
const params = new HttpParams().set('_page', "*").set('_limit', "*");
return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
}
public postTests(object) {
return this.http.post("http://localhost:3000/customers", object).subscribe(data => {console.log("POST Request is successful ", data);},error => {console.log("Error", error);});
}
}
I have my test.ts which controls my calls etc.
import { Component, OnInit } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import {FormBuilder, FormControl, FormGroup} from "#angular/forms";
import {TestService} from "./test.service";
class Customer {
id : number;
name: string;
email: string;
tel: string;
}
#Component({
selector: 'sample-template',
templateUrl: './test.component.html'})
export class TestComponent implements OnInit {
testForm: FormGroup;
testForm2: FormGroup;
public test: any;
name: string = '';
email: string = '';
tel: string = '';
public id: any;
constructor(private httpClient:HttpClient, private fb: FormBuilder, private TestService: TestService) {}
loadTasks(): void{
this.TestService.getAllTests().subscribe(response => {this.test = response;
console.log(this.test)})
}
ngOnInit() {
let trainData = [];
this.loadTasks();
this.testForm = this.fb.group({
testCd: 'Select'
});
this.testForm2 = this.fb.group({
id: this.id,
name: this.name,
email: this.email,
tel: this.tel
})
}
changeDropdown(formControl: FormControl, option: string): void {
formControl.patchValue(option);
console.log(option);
}
submitForm(){
let last:any = this.test[this.test.length-1];
this.id = last.id+1;
console.log(this.id);
this.testForm2.value.id = this.id;
console.log(this.testForm2.value);
this.TestService.postTests(this.testForm2.value);
}
}
And my html page which includes the following:
<label class="modelo-label">{{test?.testingTitle}}</label>
<form [formGroup]="testForm">
<div class="dropdown modelo-dropdown">
<label for="testCd" class="modelo-label">Testing</label>
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" role="button" id="testCd" aria-haspopup="true" aria-expanded="true">{{testForm.get('testCd').value}}</button>
<div class="dropdown-menu modelo-dropdown-menu" aria-labelledby="testCd">
<a class="dropdown-item" *ngFor="let tests of test?.trainData; let i = index" id="tests.name" (click)="changeDropdown(testForm.get('testCd'), tests.name)">{{tests.name}}</a>
</div>
</div>
<form [formGroup]="testForm2" (ngSubmit)="submitForm()">
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="name" formControlName="name" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('name').value.length !== 0}">
<label for="name">Name</label>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="email" formControlName="email" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('email').value.length !== 0}">
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="tel" formControlName="tel" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('tel').value.length !== 0}">
<label for="tel">Telephone #</label>
</div>
</div>
<div class="col-1 group generateButton">
<button class="btn btn-primary" type="submit">Submit Info</button>
</div>
</form>
My Question is, I'm have everything set up for a post and what I'm trying to do is post testForm2.value to the json but under "trainData":[{}] that's within the JSON. I'm able to do so if I just drop all other objects inside the json and have just the array after "customers":... What exactly am I missing? I'm actually confusing myself right now and I may be overthinking this by alot. The post I have currently in this code works if I have just the array after "customers":.... so instead of me passing object which is the testForm2.value what else do I need to do? I hope this makes sense.
You have some strange things in your code. First :
In you API
return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
I think what you want to do here is : (the pipe is useless you dont use it and it's not an array)
return this.http.get<Test>("http://localhost:3000/customers",{params});
In your component you want to push the update trainData list
submitForm(){
const lastTrainData = this.test.trainData[this.test.trainData.length-1];
const newTrainData = this.testForm2.value;
newTrainData.id = lastTrainData.id + 1;
this.test.trainData.push(newTrainData);
this.TestService.postTests(this.test);
}

Writing user input from angular 4 to mysql through node.js

What i'm trying to achieve is to send user input from a textbox, send that data to node.js after the enter button is clicked, which then writes that value into my specified mysql table. I just need to be able to post into the database not read back. At this point I just want the user to be able to enter 1 value (so page doesn't have to go back to allow user to enter more then 1 value). Thank you in advance.
Hero-form.component.html
<div class="container">
<div [hidden]="submitted">
<h1>Hero Form</h1>
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Name is required
</div>
</div>
<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
</form>
</div>
<div [hidden]="!submitted">
<h2>You submitted the following:</h2>
<div class="row">
<div class="col-xs-3">Name</div>
<div class="col-xs-9 pull-left">{{ model.name }}</div>
</div>
<br>
<button class="btn btn-primary" (click)="submitted=false">Edit</button>
</div>
</div>
Hero-form.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Hero } from '../recipe';
import { Observable } from 'rxjs/Observable';
import { catchError, map, tap } from 'rxjs/operators';
#Component({
selector: 'app-hero-form',
templateUrl: './hero-form.component.html',
styleUrls: ['./hero-form.component.css']
})
export class HeroFormComponent implements OnInit {
private heroesUrl = 'http://localhost:8081';
constructor(private http: HttpClient) { }
ngOnInit() {
}
powers = ['Really Smart', 'Super Flexible',
'Super Hot', 'Weather Changer'];
model = new Hero(18, 'Dr IQ');
submitted = false;
onSubmit(hero: Hero): Observable<Hero>{
return this.http.post<Hero>(this.heroesUrl, hero)
}
/*onSubmit(hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}*/
newHero() {
this.model = new Hero(42, '');
}
}
App.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HeroFormComponent } from './hero-form/hero-form.component';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
declarations: [
AppComponent,
HeroFormComponent
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }
database.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//app.use(express.json());
//app.use(express.urlencoded());
//app.use(app.router);
app.use(express.static('public'));
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234',
database : 'mydb'
});
connection.connect();
// Put
app.post('/heroes', function(req, res){
// console.log('read after this');
connection.query("INSERT INTO heroes (herolist) VALUES ?", function(err, result){
console.log(res);
if(err) {
// console.log("Error in database for put");
} else {
// console.log("Added successfully");
}
})
})
app.listen(8081, function () {
console.log('Example app listening on port 8081');
});

http in angular 2,unable to add records to database

I am trying to post the form data to my database using Angular2 but only the null values are inserted to my database.I am new to angular can someone find the error in my code
My template,
<form (ngSubmit)="onSubmit()" [(ngFormModel)]="form" #f="ngForm">
<div class="form-row">
<div class="formHeading">Facebook</div>
<input type="text" id="fb" ngControl="facebook">
<div class="errorMessage" *ngIf="f.form.controls.fb.touched && !f.form.controls.fb.valid"> Facebook address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Google</div>
<input type="text" id="gl" ngControl="google" >
<div class="errorMessage" *ngIf="f.form.controls.gl.touched && !f.form.controls.gl.valid">Google address is required</div>
</div>
<div class="form-row">
<div class="formHeading">Twitter</div>
<input type="text" id="twt" ngModel = f.twitter >
</div>
<div class="form-row">
<div class="formHeading">LinkedIn</div>
<input type="text" id="li" >
</div>
<div class="form-row">
<button type="submit" [disabled]="!f.form.valid">Save</button>
</div>
</form>
My Component
import {Component} from '#angular/core';
import {FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES} from '#angular/common';
import {Http, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
#Component({
selector: 'social-form',
directives:[FORM_DIRECTIVES],
templateUrl: './components/social/social.html',
providers: [FormBuilder]
})
export class Social {
http: Http;
form;
payLoad = null;
constructor(fb: FormBuilder) {
this.form = fb.group({
"fb": ['', Validators.required],
"gl": ['',Validators.required],
});
}
constructor(http: Http) {
this.http = http;
}
onSubmit() {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost/a2server/index.php/profile/addsocial', JSON.stringify({?????????????}),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.form = res);
}
}
class Person{
facebook:string;
google:string;
twitter:string;
linkedin:string;
}
What should i need to keep in json stringify?
Here i want validations,so i put a constructor similarlly i need http, am i need another constructor?If yes where should i put it since i cannot put two constructors in one component.