我使用角度6,我跟随
this video tutorial提交图像.
我的组件中有这个
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; } } });
这很好用.
我现在尝试将其分成两部分.将帖子及其标题及其参数转换为我的服务中的函数,只需订阅并获取组件中的结果.我试着这样做:
myapp.component.ts
this.myService.uploadImage(form).subscribe( e=>{ console.log('e- ',e); } );
在我的服务
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',observe:'events',headers:headers}); }
VScode说类型为{reportProgress:boolean; observe:string; headers:Headers}的参数不能赋予RequestOptionsArgs类型的参数
在编译期间,我得到的对象文字可能只指定已知属性,并且“ReportOroggs”类型中不存在“reportProgress”.当我尝试使用表单时,我只返回最终的响应对象,中间没有事件信息.
那么,我该如何正确设置RequestOptionsArgs呢?
谢谢
我认为你正在混合API,reportProgress是HttpRequest的属性< T>它位于@ angular / common / http中.
原文链接:https://www.f2er.com/angularjs/141091.html在您的示例中,您似乎将服务基于@ angular / http中的HttpModule的Angular 6 Http可注入服务.
>相反,使用来自@ angular / common / http的HttpClient的请求方法.
>另外,请确保使用@ angular / common / http中的HttpHeaders.
以下将有效:
uploadImage(data) { let formData = new FormData(data); let headers = new HttpHeaders().append('Authorization',this.token); return this.httpClient.post( 'http://localhost:3000/cms/upload',{ reportProgress: true,observe: 'events',headers: headers }); }
当然你必须导入:
import { HttpClient,HttpHeaders } from '@angular/common/http';
并在服务构造函数中注入HttpClient:
constructor(private httpClient: HttpClient) { ... }
我希望这能解释并解决你的问题!