gpt4 book ai didi

javascript - 取消订阅以 Angular 6 可观察到的上传停止上传进度但不是实际上传

转载 作者:行者123 更新时间:2023-11-30 19:50:28 24 4
gpt4 key购买 nike

当我尝试通过取消订阅来取消上传时,实际上我取消订阅了上传进度,但实际上传并未取消并继续上传到服务器。上传.components.ts

import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
import { Subject, Subscription, Observable } from 'rxjs';
import { HttpEventType } from '@angular/common/http';
import { UploadService } from '../../../services';
import { takeUntil } from 'rxjs/operators';

@Component({
selector: 'app-image-upload-item',
templateUrl: './image-upload-item.component.html',
styleUrls: ['./image-upload-item.component.scss']
})
export class ImageUploadItemComponent implements OnInit, OnDestroy {
@Input() index: any;
@Output() uploadSuccess: EventEmitter<any>;
@Output() uploadCanceled: EventEmitter<any>;
public localimageURL: string;
public uploadProgress: number;
public isUploadCompleted: boolean;
public uploadImageObservable: Subscription;
public isReadyForUpload: boolean;
public isUploading: boolean;
public progressMode: string;
public readonly unique: string = Math.floor((Math.random() *
100)).toString();
public readonly imagePreviewID = 'imagePreview' + this.unique;


_file: any;
@Input() public set file(value: any) {
const reader = new FileReader();
reader.onload = (e: any) => {
this.localimageURL = e.target.result;
};
this._file = value;
reader.readAsDataURL(this._file);
console.log(this._file);


}
constructor(private uploadService: UploadService) {
this.uploadProgress = 0;
this.isUploading = false;
this.localimageURL = '';
this.isUploadCompleted = false;
this.uploadSuccess = new EventEmitter<any>();
this.uploadCanceled = new EventEmitter<any>();
this.progressMode = 'indeterminate';
}

ngOnInit() {
this.uploadImageToServer(this._file);

// setTimeout(() => {
// console.log('im in set time out unsubscripting',
this.uploadImageObservable);
// this.uploadImageObservable.forEach(subscription => {
// subscription.unsubscribe();
// });
// }, 100);
}

ngOnDestroy() {
console.log('component destroyed');
this.uploadImageObservable.unsubscribe();
}
public clearUploadButtonClicked() {
// if (this.uploadImageObservable !== undefined) {
// console.log('image observable is defined');
// this.uploadImageObservable.unsubscribe();
// console.log(this.uploadImageObservable.closed);
// }
// this.uploadImageObservable.unsubscribe();
this._file = '';
this.uploadCanceled.emit({ index: this.index, uploaded: false });
}

public get showUploadProgress(): boolean {
return this.uploadProgress !== 0;
}


public uploadImageToServer(file) {
this.isUploading = true;
const progress = new Subject<number>();
progress.subscribe(value => {
this.uploadProgress = value;
});

this.uploadImageObservable = this.uploadService.uploadImage(file)
.subscribe(result => {
const type = result.type;
const data = result.data;
console.log(result);

if (type === HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * data.loaded / data.total);
progress.next(percentDone);
if (percentDone === 100) {
this.progressMode = 'indeterminate';
}
} else if (type === HttpEventType.Response) {
if (data) {
progress.complete();
this.progressMode = 'determinate';
this.isReadyForUpload = false;
this.isUploadCompleted = true;
this.isUploading = false;
this.uploadSuccess.emit({ index: this.index, mediaItem: data });
}

}
}, errorEvent => {
});
}

}

上传服务.ts

  public uploadImage(imageFile: File): Observable<any> {
const formData: FormData = new FormData();
if (imageFile !== undefined) {
formData.append('image', imageFile, imageFile.name);

const req = new HttpRequest('POST', environment.uploadImageEndPoint,
formData, {
reportProgress: true,
});

return new Observable<any>(observer => {
this.httpClient.request<any>(req).subscribe(event => {
if (event.type === HttpEventType.Response) {
const responseBody = event.body;
if (responseBody) {
this.alertService.success(responseBody.message);
observer.next({ type: event.type, data: new
MediaItem(responseBody.mediaItem) });
}
} else if (event.type === HttpEventType.UploadProgress) {
observer.next({ type: event.type, data: { loaded: event.loaded, total:
event.total } });

} else {
observer.next(event);
}
}, errorEvent => {
if (errorEvent.status === 400) {
this.alertService.error(errorEvent.error['image']);
} else {
this.alertService.error('Server Error, Please try again later!');
}
observer.next(null);
});
});
}
}

如何使用可观察取消订阅正确取消上传请求注意我已经尝试过管道 takeuntil() 并且没有任何改变

最佳答案

您要做的是在 http 请求返回 observable 上返回管道函数的结果。现在你有多个流,组件的取消订阅只是取消订阅包装 http 请求可观察(未连接)的可观察。

你会想做这样的事情:

return this.httpClient.request<any>(req).pipe(
// use rxjs operators here
);

然后您将使用 rxjs operators (I've been doing this for a while, but I still highly reference this site)执行任何所需的逻辑并反射(reflect)诸如错误之类的事情并将进度上传到调用服务的组件。在组件端,您将保留订阅/取消订阅逻辑。

例如,您可以使用 switchMap operator转换从可观察到的 http 请求返回到组件的内容,并指定要返回到组件的值,以及 catchError相应地对任何错误使用react。

return this.httpClient.request<any>(req).pipe(
switchMap(event => {
if (event.type === HttpEventType.Response) {
const responseBody = event.body;
if (responseBody) {
this.alertService.success(responseBody.message);
return { type: event.type, data: new MediaItem(responseBody.mediaItem) };
}
} else if (event.type === HttpEventType.UploadProgress) {
return { type: event.type, data: { loaded: event.loaded, total: event.total } };
}
return event;
}),
catchError(errorEvent => {
if (errorEvent.status === 400) {
this.alertService.error(errorEvent.error['image']);
} else {
this.alertService.error('Server Error, Please try again later!');
}
return of(<falsy or error value>);
}),
);

或者您可以在this example 之后对其进行更多建模。只需将来自服务的 http 函数调用返回到组件并在那里处理订阅中的事情。

关于javascript - 取消订阅以 Angular 6 可观察到的上传停止上传进度但不是实际上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54533920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com