Angular 4 中如何使用从其他组件获取的数据提交表单

how to submit form with fetched data from other component in Angular 4

有书和作者两个组成部分

书籍表格创建和post数据

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'));
  }

此处 select 框能够获取数据,但是 post 仅名称获取 post 成功,但 select 框中获取的作者组件的作者未成功连同姓名一起提交。

我想你可以把[(ngModel)]="selectedAuthor"改成[(ngModel)]="selectedAuthor._id"如果你只想在post-request中发送id属性,否则你发送整个author-object,而不仅仅是您要发送的 属性。

试试这个

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";

然后将 HttpModule 导入 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);
    }

}

如果您想使用 HttpClient,请查看下面链接的演示。

Demo with Http and HttpClient

由于要将书名和作者id都传给服务器端,可以按照上面的代码。我已经用作者 select 的虚拟值测试了这段代码。我已经检索到书名和作者 ID 到 http post。如果它仍然没有进入服务器端,那么服务器端应该有一些问题。请检查。

希望对您有所帮助。如果您有任何问题或建议,请告诉我。