import { Injectable } from "@angular/core";
import { Book } from "../models/book/book";
import { Observable, of, BehaviorSubject } from "rxjs";
import { skip } from "rxjs/operators";
@Injectable({
providedIn: "root"
})
export class BooksService {
private books$$ = BehaviorSubject<Book[]>([]);
private editingBook$$ = BehaviorSubject<Book>(null) // book that needs to edit
public books$ = this.books$$.asObservable();
public editingBook$ = this.editingBook$$.asObservable();
constructor() {
const savedBooks = (() => {
try {
return JSON.parse(localStorage.getItem("books"));
} catch (e) {
return [];
}
})(); // iife as safeguard for JSON.parse
if (Array.isArray(savedBooks)) {
this.books$$.next(savedBooks);
}
this.books$.pipe(skip(1)).subscribe(books => this.saveChanges(books)); // skip initial null or already saved value
}
addBook(book: Book): void {
const books = this.books$$.value; // optionally const books = this.books$$.value.slice();
books.push(book);
this.books$$.next(books);
}
deleteBook(book: Book): void {
const books = this.books$$.value;
const index = books.findIndex(item => item.author === book.author);
books.splice(index, 1);
this.books$$.next(books);
}
editBook(book: Book): void {
this.editingBook$$.next(book);
}
private saveChanges(books: Book[]): void {
localStorage.setItem("books", JSON.stringify(books));
}
}
constructor(private src: BooksService) {}
constructor(
private booksService: BooksService,
) {}
В вашем коде Person.constructor()
return this
вернет вам Person конечно же.Это не варианты обхода проблемы, это как корректно сделать. Проблемы тут никакой нет.