I use Subject in my app in order to make CRUD operations. I subscribe to it in a couple of components, but it doesn't seem to change my values in real time. I have to resort to reloading the page to get the most recent values. This is probably due to my lack of understanding of how everything should be organised, but I haven't found any simmilar issues here. Could you please help me fix what I do wrong? (using BehaviourSubject yields the same results). Here is the code for my service:
@Injectable({ providedIn: 'root' })
export class AppBookshelfService {
filesAndFolders: ItemFile[] = [];
filteredArrOfFolders = [];
filesSubj = new Subject();
curentParent = 0;
getFiles() {
this.http.get<any>('http://localhost:3000/api/items').subscribe(
(data: any) => {
this.filesAndFolders = data.items;
this.filesAndFolders = data.items.filter(item => item.isDeleted === 0);
this.filesSubj.next(data.items.filter(item => item.isDeleted === 0));
data.items.forEach(item => {
if(item.parentId !== 0 && item.isFolder === 1) {
this.filteredArrOfFolders.push(item);
}
}); }
)
}
getFile(id: number): Observable<ItemFile> {
return this.http.get<ItemFile>("http://localhost:3000/api/items/" + id);
}
emitIdForFile(parentId: number) {
this.curentParent = parentId;
}
getCurentParent() {
return this.curentParent;
}
postFile(item: ItemFile) {
return this.http.post<ItemFile>("http://localhost:3000/api/items/", item).subscribe(result => {})
}
Here is the code of one of my key components, that does the subscribing:
ngOnInit(): void {
this.bookshelfService.getFiles();
this.sub = this.bookshelfService.filesSubj.subscribe(data => {
this.files = data;
console.log(this.files)
let groupOfCheckboxes = {};
this.files.forEach(element => {
groupOfCheckboxes[element.id.toString()] = new FormControl("");
});
this.checkboxForm = new FormGroup(groupOfCheckboxes);
});
// this.getFolders();
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}
startCreatingFolder() {
this.isFolderBeingCreated = !this.isFolderBeingCreated;
}
createFile(id: number) {
this.bookshelfService.emitIdForFile(id);
this.router.navigate(['create']);
}
createFolder(event, id) {
const folder = {
name: this.folderNameInput.nativeElement.value,
description: "",
imageLink: "",
isDeleted: 0,
parentId: id,
isFolder: 1
}
this.bookshelfService.filesAndFolders.push(folder);
this.bookshelfService.getFiles();
this.bookshelfService.postFile(folder);
this.isFolderBeingCreated = false;
}
Here is a link to the full repository: https://github.com/Not-a-whale/BookshelfApp
Here is the app working on Heroku with the said flaw: https://bookshelf-app-nikita.herokuapp.com/