如何从Angular中的select控件中检索所选选项的ID?

时间:2019-04-25 19:07:49

标签: angular

在我的Angular应用中,我正在从此JSON文件中检索数据。

Books.json:

[
    {
    "bookID": 1,
    "title": "Goodnight Moon",
    "author": "Margaret Wise Brown",
    "publicationYear": "1953"
    },
    {
    "bookID": 2,
    "title": "Winnie-the-Pooh",
    "author": "A. A. Milne",
    "publicationYear": "1926"
    }
]

这是我用来读取JSON的代码:

add-reader.component.ts:

ngOnInit() {
    this.dataService.getAllBooks()
        .subscribe(
          (data: Book[]) => this.allBooks = data,
          (err: any) => console.log(err),
          () => console.log('all done getting books')
    );
   }

然后,我将像这样成功地填充选择控件:

add-reader.component.html

<select name="bookDropDown" ngModel>
    <option [ngValue]="book.bookID" *ngFor="let book of allBooks">
        {{book.title}}
    </option>
</select>

提交表单后,将执行以下代码:

add-reader.component.ts

saveReader(formValues: any): void {
    let newReader: Reader = <Reader>formValues;
    newReader.readerID = 0;

    this.dataService.addReader(newReader)
    .subscribe(
      (data: Reader) => console.log(data),
      (err: any) => console.log(err)
    );
  }

data.service.ts:

addReader(newReader: Reader): Observable<Reader> {
    return this.http.post<Reader>('/api/readers', newReader, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    });
  }

reader.js:

router.route('/')
.post(function(req, res) {
var data = getReaderData();
var nextID = getNextAvailableID(data);
var newReader = {
            readerID: nextID,
            name: req.body.name,
            weeklyReadingGoal: req.body.weeklyReadingGoal,
            totalMinutesRead: req.body.totalMinutesRead,
            bookID: req.body.bookID
};
data.push(newReader);

saveReaderData(data);
res.status(201).send(newReader);
});

提交表单时,我将推送到 readers.json ,其中包含以下几个对象:

 {
    "readerID": 1,
    "name": "Maria",
    "weeklyReadingGoal": 350,
    "totalMinutesRead": 5600,
    "bookID": 91
}

当前,当我提交表单时,将添加除 bookID 之外的所有值。

如何从Select控件中传递bookID以便它填充JSON文件?

非常感谢!

0 个答案:

没有答案