There are two components book and author
book form creates and post data
book.component.html:
<form [formGroup]="bookForm" novalidate>
<div class="form-group">
<label class="col-md-4">Book Name</label>
<input type="text" class="form-control" formControlName="name" #name/>
</div>
<div class="form-group">
<label class="col-md-4">Authors</label>
<select class="form-control" name="author" [(ngModel)]="selectedAuthor" #author [ngModelOptions]="{standalone: true}">
<option *ngFor="let author of authors" [value]="author._id" >{{author.name}}</option>
</select>
</div>
<div class="form-group">
<button (click)="addBooks(name.value,author.value)" class="btn btn-primary">Add</button>
</div>
</form>
book.component.ts
export class BookcreateComponent implements OnInit {
bookForm: FormGroup;
authors:any;
genres:any;
public selectedAuthor:string;
public selectedGenre:string;
constructor(private dataService: DataStorageService, private fb: FormBuilder, private router: Router) {
this.createForm();
}
createForm() {
this.bookForm = this.fb.group({
name: ['', Validators.required],
language: ['', Validators.required],
published: ['', Validators.required],
pages: ['', Validators.required],
author:[''],
genre:[''],
});
}
addBooks(name, author){
this.dataService.addBooks(name, language, published, pages, author, genre);
this.router.navigate(['/']);
}
getAuthors() {
this.dataService.getAuthors().subscribe(
data => { this.authors = data},
err => console.error(err),
() => console.log('author loaded')
);
}
json:
{
name:raj,
_id:3e32233edd222221
}
datastorgeservice.ts
addBooks(name,language,published,pages,author){
const obj ={
name:name,
language:language,
published:published,
pages:pages,
author:author,
};
this.http.post('http://testurl:3000/books',obj).subscribe(res=>console.log('done'));
}
Here select box able to fetch data but while posting only name is getting posted successfully but author from author component fetched in select box is not submitted along with name.
Try this
component.html
<form [formGroup]="bookForm" novalidate>
<div class="form-group">
<label class="col-md-4">Book Name</label>
<input type="text" class="form-control" formControlName="name" #name/>
</div>
<div class="form-group">
<label class="col-md-4">Authors</label>
<select class="form-control" name="author" [(ngModel)]="selectedAuthor" #author [ngModelOptions]="{standalone: true}">
<option *ngFor="let author of authors" [value]="author._id" >{{author.name}}</option>
</select>
</div>
<div class="form-group">
<button (click)="addBooks(name.value,author.value)" class="btn btn-primary">Add</button>
</div>
</form>
component.ts
bookForm: FormGroup;
authors:any;
genres:any;
public selectedAuthor:string;
public selectedGenre:string;
constructor(private fb: FormBuilder, private router: Router,private dataservice:DataStorageService) {
this.createForm();
this.getAuthors();
}
createForm() {
this.bookForm = this.fb.group({
name: ['', Validators.required],
language: ['', Validators.required],
published: ['', Validators.required],
pages: ['', Validators.required],
author:[''],
genre:[''],
});
}
addBooks(name, author){
this.dataservice.addBooks(name,author).subscribe(data=>{
console.log('done');
this.router.navigate(['/']);
});
}
getAuthors() {
this.authors=[{
name:'raj',
_id:'3e32233edd222221'
},{
name:"roje",
_id:"3e3223"
}];
}
app.module.ts
import {HttpModule} from "@angular/http";
then import the HttpModule into NgModule.
datastorageservice.ts
import {Injectable} from "@angular/core";
import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class DataStorageService {
http:Http;
constructor(http:Http){
this.http=http;
}
addBooks (name,author) :Observable<Response>{
const obj ={
name:name,
author:author // author is equal to author id
};
console.log(obj); //{name: "book1", author: "3e32233edd222221"}
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://testurl:3000/books', JSON.stringify(obj),options);
}
}
If you want to go with HttpClient then check the demo linked below.
Since you want to pass both book name and author id to the server side,you can follow the above code. I have tested this code with dummy values for the author select. I have retrieved both book name and author id up to http post. If it's still not going to server side then there should be some problems in server side. Please check.
I hope this will help you. If you have any issues or suggestion let me know.