【发布时间】:2021-01-31 10:48:50
【问题描述】:
我在我的应用程序中使用 Subject 来进行 CRUD 操作。我在几个组件中订阅了它,但它似乎并没有实时改变我的价值观。我不得不求助于重新加载页面来获取最新的值。这可能是由于我对如何组织所有内容缺乏了解,但我在这里没有发现任何类似的问题。你能帮我解决我做错了什么吗? (使用 BehaviourSubject 产生相同的结果)。 这是我的服务的代码:
@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 => {})
}
这是我的一个关键组件的代码,用于订阅:
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;
}
这里是完整存储库的链接: https://github.com/Not-a-whale/BookshelfApp
这是在 Heroku 上运行的应用程序,存在上述缺陷: https://bookshelf-app-nikita.herokuapp.com/
【问题讨论】:
标签: javascript angular typescript rxjs subject