在我的Angular应用程序中,我有一个上传页面。 上传由服务处理并由NGRX效果触发。
// service
public upload(file: File): any {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
// create a http-post request and pass the form
// tell it to report the upload progress
const request = new HttpRequest('POST', url, formData, {
reportProgress: true
});
return this.httpClient.request(request);}
// Effect
@Effect({ dispatch: false })
uploadFile = this.actions
.ofType(ActionTypes.UploadFile)
.map(toPayload)
.switchMap(file =>
this.service.upload(file).map(event => {
if (event.type === HttpEventType.UploadProgress) {
// calculate the progress percentage
const percentDone = Math.round(100 * event.loaded / event.total);
this.store.dispatch(new UpdateUploadProgressAction(percentDone));
} else if (event instanceof HttpResponse) {
if (event.status >= 400) {
console.error(event);
this.store.dispatch(new UploadFileFailureAction(event));
} else {
this.store.dispatch(new UploadFileSuccessAction(event.body));
}
}
})
);
由于上传可能需要一些时间(至少是文件的验证),我想为用户提供机会中止待处理的请求。
通常你可以使用这样的取消订阅方法:
cons sub = this.service.upload(file);
...
sub.unsubscribe();
但我不知道如何在效果中做到这一点。 有什么建议或最佳实践吗?
谢谢:)