![](/img/trans.png)
[英]How to tell an RxJS Observable timer to emit the next in sequence immediately
[英]Observable next does not emit
我有這個簡單的 function 將文件放入 S3:
putFile$(S3AuthorizationToken: S3AuthorizationToken, file: File) {
const futureFile: FutureFile = {
size: file.size,
type: file.type,
};
return combineLatest([
this.http.put(S3AuthorizationToken.signedUrl, file, {
headers: new HttpHeaders({
'Content-Type': file.type,
}),
reportProgress: true,
observe: 'events',
}),
of(futureFile),
]);
}
}
在我的組件中,我想收聽上傳進度更新:
private percentChange = new BehaviorSubject<number>(null);
percentChange$ = this.percentChange.asObservable();
onFileChange(event: Event) {
console.log(event);
const target = event.target as HTMLInputElement;
const file: File = target.files[0];
this.s3
.getS3AuthorizationToken$()
.pipe(
switchMap((S3AuthorizationToken) =>
this.s3.putFile$(S3AuthorizationToken, file)
),
map(([event, futureFile]) => {
if (event.type === HttpEventType.UploadProgress) {
const percent = Math.round((event.loaded / event.total) * 100);
console.log(`Uploading ${percent}%`);
this.percentChange.next(percent);
}
if (event.type === HttpEventType.Response) {
console.log(`Upload complete`);
this.futureFile.next(futureFile);
}
})
)
.subscribe();
}
我遇到的問題是this.percentChange.next()
和this.futureFile.next()
它似乎沒有發出任何價值。
在我的模板中,我有:
<input type="file" (change)="onFileChange($event)">
<div>{{ percentChange$ | async | json }} %</div>
你知道什么會導致這種情況嗎?
您實際上可能必須 map 直接觀察到this.s3.putFile$(S3AuthorizationToken, file)
而不是從switchMap
返回的響應。 嘗試以下
onFileChange(event: Event) {
console.log(event);
const target = event.target as HTMLInputElement;
const file: File = target.files[0];
this.s3.getS3AuthorizationToken$().pipe(
switchMap((S3AuthorizationToken) =>
this.s3.putFile$(S3AuthorizationToken, file).pipe(
map(([event, futureFile]) => {
if (event.type === HttpEventType.UploadProgress) {
const percent = Math.round((event.loaded / event.total) * 100);
console.log(`Uploading ${percent}%`);
this.percentChange.next(percent);
} else if (event.type === HttpEventType.Response) {
console.log(`Upload complete`);
this.futureFile.next(futureFile);
}
return event; // <-- return something for the `map` operator
})
)
)
)
.subscribe();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.