类型 'Observable<void>' 不可分配给类型 'Observable<HttpEvent<any>>'类型 'void' 不可分配给类型



我正在尝试添加上传进度条,但收到了这个错误。并且event.type未定义。

请帮我找到解决方案。谢谢

我已经附上了我所做的代码。

HttpRequest代码

uploadfile(file: any): Observable<HttpEvent<any>>{
return this.InfoService.getId().pipe(
concatMap((result) => {
return this.schemaService.getSchema().pipe(schema => {
const url = '/url';
return this.http.post(url, file, {headers: this.headers, reportProgress: true});
}).toPromise().then((resolved) => {
this.successMessage('Upload Success',MessageIcon, " uploaded successfully");
})
}));
}

订阅方式:


uploadfile(){
const formData = new FormData();
formData.append('file', this.uploadForm.get('item').value);
this.uploadService.uploadfile(formData).subscribe((event : HttpEvent<any>) => {
console.log(event)
switch (event.type) {
case HttpEventType.UploadProgress:
this.progress = Math.round(event.loaded / event.total * 100);
console.log(`Uploaded! ${this.progress}%`);
break;
case HttpEventType.Response:
console.log('successfull!', event.body);
setTimeout(() => {
this.progress = 0;
}, 1500);
}
})  
}
  1. 我不确定您要如何处理pipe函数的schema参数。pipe以RxJS运算符作为自变量。根据用法判断,我假设您希望在这里使用像concatMap这样的映射运算符。

  2. 函数的返回类型声明为Observable<HttpEvent<any>>。但是您正在使用toPromise()函数将Observable转换为Promise。您可以改用tap运算符。

尝试以下

uploadfile(file: any): Observable<HttpEvent<any>> {
return this.InfoService.getId().pipe(
concatMap((result) => this.schemaService.getSchema()),
concatMap((schema) => {
const url = '/url';
return this.http.post(url, file, {
headers: this.headers,
reportProgress: true,
observe: "events"              // <-- also try adding `observe`
});
}),
tap(() => this.successMessage('Upload Success', MessageIcon, " uploaded successfully"))
);
}

相关内容

最新更新