export class BooksService {
private books: Book[];
private editingBook: Book = { author: "", title: "", year: 0, pages: 0 }; // внести какие-то данные
...
import { Injectable } from "@angular/core";
import { Book } from "../models/book/book";
import { Observable, of } from "rxjs";
@Injectable({
providedIn: "root"
})
export class BooksService {
private books: Book[];
private editingBook: Book; // book that needs to edit
constructor() {
this.books = JSON.parse(localStorage.getItem("books")) || [];
}
getBooks(): Observable<Book[]> {
return of(this.books);
}
getEditingBook(): Observable<Book> {
return of(this.editingBook);
}
addBook(book: Book): void {
this.books.push(book);
this.saveChanges();
}
deleteBook(book: Book): void {
const index = this.books.findIndex(item => item.author === book.author);
this.books.splice(index, 1);
this.saveChanges();
}
editBook(book: Book): void {
this.editingBook = book;
}
private saveChanges(): void {
localStorage.setItem("books", JSON.stringify(this.books));
}
}
import { Component, OnInit } from "@angular/core";
import { Book } from "src/app/models/book/book";
import { BooksService } from "src/app/services/books.service";
@Component({
selector: "app-form",
templateUrl: "./form.component.html",
styleUrls: ["./form.component.sass"]
})
export class FormComponent implements OnInit {
newBook: Book = {
author: "",
title: "",
year: 0,
pages: 0
};
editingBook: Book;
constructor(private src: BooksService) {}
ngOnInit() {
this.getEditingBook();
}
getEditingBook(): void {
this.src.getEditingBook().subscribe(book => {
this.editingBook = book;
console.log(book);
});
}
handleNewBook(): void {
this.src.addBook(this.newBook);
this.resetNewBook();
}
private resetNewBook(): void {
this.newBook = {
author: "",
title: "",
year: 0,
pages: 0
};
}
}
2. Не позволяйте добавлять дубликат товара. Вместо этого увеличивайте количество.
Была идея с добавлением свойства, например, count, потом тупо умножать цену на count и получать нормальный результат, но в React компоненты неизменяемы.