以角度上传文件后刷新表格列表



我们的上传应用程序中有3个选项卡 - 主页,上传,文件列表。我们为 3 个选项卡创建了单独的组件。上传文件后,您需要刷新整个页面才能看到更改。上传后应自动刷新表列表。

uploadlist.component.ts

ngOnInit() {
this.getFileList();
};
getFileList() {
this.showError = false;
this._uploadlistService.getFiles().subscribe((costSpreadsheet) => {
console.log(costSpreadsheet);
this.costSpreadsheet = costSpreadsheet;
this.showLoader = false;
},
(error) => {
console.log('Error fetching file list');
this.response = error;
this.showLoader = false;
this.showError = true;
});
}

upload.component.ts

onSubmit() {
this.response = ('Please select a file first. ');
this.showError = true;
if (this.fileToUpload.name != null){
this.showLoader = true;
this.showSuccess = false;
this.showError = false;
console.log(this.fileToUpload.name);
this.fileUploadService.fileUpload(this.fileToUpload)
.subscribe( data => {
console.log('Successful upload');
this.response = 'Upload Successful';
this.showLoader = false;
this.showSuccess = true;    
},
(error) => {
console.log('Error Uploading file');
this.response = error;
this.showLoader = false;
this.showError = true;
}
);
}
}

uploadlist.service.ts

getFiles(): Observable<CostSpreadsheet[]> {
return this._http.get<CostSpreadsheet[]>(this.uploadUrl + "/spreadsheet/" + this.uploader)
.pipe(catchError(this.handleError<any>('getFiles')));
}

我尝试在upload.component.ts中复制getFileList((方法的内容,以便它在上传后刷新文件列表。它确实更新了列表(在后端(,但视图仍然相同。

我正在从 db2 数据库中获取数据,我们使用 Spring 引导作为后端代码。我使用可变成本电子表格获得它,并且我还有一个角度模型文件,其中它标识了我需要的后端重要数据,例如文件名、总记录和总金额。

在您的uploadlist.component.ts中,方法getFiles只被调用一次,这就是您的列表不更新的原因。

最简单的方法是通知列表更新其内容。

为此,您可以使用主题:

uploadlist.service.ts

public updateList$: Subject<void> = new Subject();

成功上传文件后,请在upload.component.ts中就该主题致电.next()

在你的uploadlist.component.ts中:

ngOnInit() {
this.getFileList();
this. _uploadlistService.updateList$.subscribe(() => {
this.getFileList(); // Get the current files
});
}

否则,您不必一遍又一遍地调用getFileListe,而是可以通过主题发出上传的文件并更新CostSpreadsheet数组。

从提供的代码中,很难看出哪个变量绑定到您尝试显示的数据。

当您从订阅中获取数据时,您应该执行以下操作:

this.someservice.subscribe((data) => {
this.myDataToDisplay = data
})

您可以订阅多个组件,以便表示选项卡的所有组件都应以这种方式订阅,当服务发出新数据时,所有组件都应更新。您应该在每个组件的 ngOnInit 方法中订阅。

如果组件不存在,以至于当服务发出新数据时它们不侦听,则可能需要考虑在服务中使用 RxJS 行为主体或使用全局存储解决方案(如 ngrx 存储(。

最新更新