#html #angular #typescript
#HTML #угловой #typescript
Вопрос:
Я пытаюсь передавать данные своих книг каждый раз, когда нажимаю кнопку «Сводка», но она передает только данные первой книги, все остальные, на которые я нажимаю кнопку, по-прежнему показывают данные первой книги.
book.component.html
<body>
<div class="search-hero">
<input class="form-control" type="text" name="search" [(ngModel)]="searchText" autocomplete="off"
placeholder="amp;#61442; Start searching for a book by name, price or type" />
</div>
<div class="container" *ngFor="let item of books | filter: searchText">
<img src="{{ item.image }}" alt="img" class="image" />
<div class="overlay overlayFade">
<div class="text">
<label>Book Name</label>
<input type="text" class="form-control" placeholder="Enter name" [(ngModel)]="item.name"
[disabled]="isAfford ? false : true" />
<label>Category</label>
<input type="text" class="form-control" placeholder="Enter category" [(ngModel)]="item.category"
[disabled]="isAfford ? false : true" />
<label>Price</label>
<input type="number" class="form-control" placeholder="Enter price" [(ngModel)]="item.price"
[disabled]="isAfford ? false : true" />
<label>Amount</label>
<input type="number" class="form-control" placeholder="Enter amount" [(ngModel)]="item.amount"
[disabled]="isAfford ? false : true" />
<button class="btn btn-primary" *ngIf="canPurchase" (click)="purchaseBook(item)">
Purchase
</button>
<button class="btn btn-warning" (click)="updateBook(item)" *ngIf="isAfford">
Update
</button>
<button class="btn btn-danger" (click)="deleteBook(item.id)">
Delete
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Summary
</button>
<div class="alert alert-success" *ngIf="message">{{ message }}</div>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{{item.name}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">amp;times;</span>
</button>
</div>
<div class="modal-body">
{{item.summary}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</body>
books.component.ts
import { CustomerService } from './../../services/customer.service';
import { AdminService } from './../../services/admin.service';
import { LoginService } from './../../services/login.service';
import { AuthorService } from './../../services/author.service';
import { Book } from './../../models/book';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-books',
templateUrl: './books.component.html',
styleUrls: ['./books.component.css'],
})
export class BooksComponent implements OnInit {
modalForm: FormGroup;
searchText: string;
message: string;
public canPurchase = false;
public authorID: number;
public email: string;
public password: string;
public book = new Book();
public books: Book[] = [];
public type: string;
public isAfford = false;
id: number = 0;
constructor(
private authorService: AuthorService,
private activateRoute: ActivatedRoute,
private loginService: LoginService,
private router: Router,
private adminService: AdminService,
private customerService: CustomerService
) { }
ngOnInit(): void {
this.type = this.loginService.type;
if (this.type === 'Author') {
this.authorService
.getAuthorID(this.loginService.email, this.loginService.password)
.subscribe(
(res) => {
this.authorID = res;
this.getAllBooks();
},
(err) => {
alert(err.message);
}
);
this.isAfford = true;
}
if (this.type === 'Admin') {
this.id = 1;
this.isAfford = false;
this.getAllBooks();
}
if (this.type === 'Customer') {
this.customerService
.getCustomerID(this.loginService.email, this.loginService.password)
.subscribe(
(res) => {
this.id = res;
this.getAllBooks();
},
(err) => {
alert(err.message);
}
);
this.canPurchase = true;
}
}
resetForm() {
this.modalForm.reset();
console.log('reset');
}
addBook() {
this.router.navigateByUrl('add-book');
}
getOneBook(id: number) {
this.authorService.getOneBook(id).subscribe(
(res) => {
this.book = res;
},
(err) => {
alert(err.message);
}
);
}
purchaseBook(book: Book) {
this.customerService.setCustomerID(this.id).subscribe(
(res) => {
this.customerService.purchaseBook(book).subscribe(
(res) => {
this.router.navigateByUrl('purchases');
},
(err) => {
alert(err.message);
}
);
},
(err) => {
alert(err.message);
}
);
}
updateBook(book: Book) {
this.authorService.updateBook(book).subscribe(
(res) => {
this.book = res;
this.message = book.name ' update successfully!';
setTimeout(() => {
this.message = '';
} , 2000);
},
(err) => {
alert(err.message);
}
);
}
deleteBook(id: number) {
this.authorService.deleteBook(id).subscribe(
(res) => {
this.books = this.books.filter((book) => book.id !== id);
},
(err) => {
alert(err.message);
}
);
}
getAllBooks() {
if (this.type === 'Author') {
this.authorService.getAllBooks(this.authorID).subscribe(
(res) => {
this.books = res;
},
(err) => {
alert(err.message);
}
);
}
if (this.type === 'Admin' || this.type === 'Customer') {
this.adminService.getAllBooks().subscribe(
(res) => {
this.books = res;
},
(err) => {
alert(err.message);
}
);
}
}
}
Мне отображаются только данные первой книги, но если я нажму на краткое изложение других книг, оно все равно покажет мне данные первой книги. спасибо за помощников
Комментарии:
1. Вы используете одно и то же
ID
для всех модалов, попробуйте изменить разделы идентификаторов на[id]="'modal-' index"
и индекс на цикл.2. Лучше иметь общий модальный и запускать модальный из файла ts, чтобы у вас не было кучи разметки в браузере, когда в цикле так много книг..