【发布时间】:2021-01-27 18:56:15
【问题描述】:
我已经为 POST 方法编写了 API。它创建新书并将这本书分配给指定的作者。 (多对多关系)。当我使用 Postman 时,一切正常......但不能从客户端(Angular)工作,见下文
POST REQUEST
BODY
{
"title": "Sample Title",
"isbn": "123-41-5-12311",
"publisherId": 1,
"category": "Drama",
"authors": [
{ "authorId": 5 },
{ "authorId": 2 },
{ "authorId": 1 }
]
}
JSON RESULT
{
"title": "TEST WTOREK55",
"isbn": "123-41-5-12311",
"category": "Err",
"publisherId": 1,
"authors": [
{
"authorId": 5
},
{
"authorId": 2
},
{
"authorId": 1
}
]
}
我会尝试解释我面临的问题。 现在我正在尝试将此功能移至客户端。我正在使用角。我的问题是我不知道如何将这些带有“authorIds”的“作者”列表从表单传递给控制器。当我调试时,即使我在表单中指定了 authorId,我仍然会得到空的“作者”。
这是我的 add-edit-book.component.ts
export class AddEditBookComponent implements OnInit {
constructor(private service: SharedService) { }
@Input() book: any;
bookId: number;
title: string;
authorId: number;
isbn: string;
publisherId: number;
category: string;
PublisherList: any[];
AuthorList: any[];
ngOnInit(): void {
this.refreshPublisherList();
this.refreshAuthorList();
this.bookId = this.book.bookId;
this.title = this.book.title;
this.authorId = this.authorId;
this.isbn = this.book.isbn;
this.publisherId = this.book.publisherId;
this.category = this.book.category;
}
refreshAuthorList() {
this.service.getAuthors().subscribe(data => {
this.AuthorList = data;
});
}
refreshPublisherList() {
this.service.getPublishers().subscribe(data => {
this.PublisherList = data;
});
}
addBook() {
var val = {
title: this.title,
authorId: this.authorId,
isbn: this.isbn,
publisherId: this.publisherId,
category: this.category
};
this.service.addBook(val).subscribe(res => {
});
}
}
和html端(作者部分)
<label class="col-sm-2 col-form-label">Author</label>
<div class="col-sm-10 mb-1">
<!-- <input type="text" class="form-control" [(ngModel)]="publisher" placeholder="Publisher"> -->
<div>
<select class="form-control" [(ngModel)]="authorId">
<option *ngFor="let item of AuthorList" value="{{item.authorId}}">{{item.authorName}} {{item.authorLastName}}
</option>
</select>
</div>
</div>
我也粘贴了我的 BookController 和 POST 方法。
[HttpPost]
public async Task<IActionResult> AddBook([FromBody] BookForNewDto bookForNewDto)
{
var bookToCreate = _mapper.Map<Book>(bookForNewDto);
var bookToReturn = _mapper.Map<BookForNewDto>(bookToCreate);
var bookToAdd = await _context.Books.AddAsync(bookToCreate);
await _context.SaveChangesAsync();
var bookIdToAdd = bookToCreate.BookId;
var authorIdToAdd = bookForNewDto.Authors.Select(aa => aa.AuthorId).ToList(); // throwing error here, while adding via Client side, but not throwing while using Postman
foreach (var item in authorIdToAdd)
{
var bookAuthorToAdd = new BookAuthor()
{
BookId = bookIdToAdd,
AuthorId = item
};
var newBookAuthor = _context.BooksAuthors.AddAsync(bookAuthorToAdd);
}
await _context.SaveChangesAsync();
return Ok(bookToReturn);
}
我不知道我是否正确地提出了这个问题,但我的问题是:如何将 authorsId 的列表从 Angular 控制器传递给 JSON 正文?我是 Angular 的新手,所以如果我的问题很琐碎或搞砸了,请原谅。
【问题讨论】:
标签: c# angular api asp.net-web-api .net-core