0

I have written API for POST method. It creates new book and assign this book to speified authors. (many-to-many relationship). Everything works when I am using Postman... but is not working from Client side (Angular) see below

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
        }
    ]
}

I'll try explain what i am facing with. Now I am trying to move this functionality to Client side. I am using Angular. My problem is I dont know how to pass these 'authors' list with 'authorIds' from the form to the controller. When Im debugging I am still getting empty 'authors' even I specify authorId in the form.

This is my 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 => {
    });
  }
}

And html side (Author section)

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

I paste my BookController and POST method too.

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

I dont know if i am properly asking the question but my question is: How to pass list of the authorsId's to the JSON body from Angular controller? I am new with the Angular, so please forgive if my question is trivial or messed up.

1 Answer 1

1

You have to create the array before sending to the service, exactly like the JSON you shared with us.

var val = {
      title: this.title,
      authors: [{authorId: this.authorId}],
      isbn: this.isbn,
      publisherId: this.publisherId,
      category: this.category
};
this.service.addBook(val).subscribe(res => {
        /* do whatever you want with the response */
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.