我使用角度6,我跟随这个视频教程提交图像.
我想观察表单提交的进度,这样我就可以得到上传文件的百分比.
我的组件中有这个
import { HttpClient,HttpEventType } from '@angular/common/http';
import { Http, Headers } from '@angular/http';
constructor(
private formBuilder: FormBuilder,
private myService:MyService,
private changeDetector: ChangeDetectorRef,
private carouselConfig : NgbCarouselConfig ,
private http:HttpClient
) { }
let headers = new Headers();
headers.append('Authorization',this.token);
let eb =null;
this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true,observe:'events'}).subscribe(
event=>{
if(event.type === HttpEventType.UploadProgress){
let pv = Math.round(event.loaded / event.total *100);
this.imguploadprogress.nativeElement.value = pv;
}
else if(event.type === HttpEventType.Response){
eb = event.body;
if(eb.success){
this.imguploadprogress.nativeElement.value = 100;
this.imageMsg='All good';
}
else{
this.imguploadprogress.nativeElement.value = 0;
this.imageMsg='nope;
}
}
});
Run Code Online (Sandbox Code Playgroud)
这很好用.
我现在尝试将其分成两部分.将帖子及其标题及其参数转换为我的服务中的函数,只需订阅并获取组件中的结果.我试着这样做:
myapp.component.ts
this.myService.uploadImage(form).subscribe(
e=>{
console.log('e- ',e);
}
);
Run Code Online (Sandbox Code Playgroud)
在我的服务
myapp.service.ts
uploadImage(data) {
let formData = new FormData(data);
let headers = new Headers();
headers.append('Authorization',this.token);
return this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true, observe:'events', headers:headers});
}
Run Code Online (Sandbox Code Playgroud)
VScode说 Argument of type {reportProgress:boolean;observe:string;headers:Headers} is not assingable to parameter of type RequestOptionsArgs
在编译期间,我得到Object literal may only specify known properties, and 'reportProgress' does not exist in type 'RequestOptionsArgs'.并且当我尝试使用表单时,我只返回最终的响应对象,中间没有事件信息.
那么,我该如何正确设置RequestOptionsArgs呢?
谢谢
我认为您正在混合 API,这reportProgress是.HttpRequest<T>@angular/common/http
在您的示例中,您的服务似乎基于 Angular 6可Http注入服务。HttpModule@angular/http
相反,请使用中的request方法。HttpClient@angular/common/http
另外,请确保您也使用HttpHeadersfrom 。@angular/common/http
以下将起作用:
uploadImage(data) {
let formData = new FormData(data);
let headers = new HttpHeaders().append('Authorization', this.token);
return this.httpClient.post(
'http://localhost:3000/cms/upload',
formData,
{
reportProgress: true,
observe: 'events',
headers: headers
});
}
Run Code Online (Sandbox Code Playgroud)
当然,您必须导入:
import { HttpClient, HttpHeaders } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)
并HttpClient在您的服务构造函数中注入:
constructor(private httpClient: HttpClient) { ... }
Run Code Online (Sandbox Code Playgroud)
我希望这能解释并解决您的问题!
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |