2017-05-09 67 views
2

我在邮递员中发送文件和其他参数的类型为“form-data”,它工作正常。我想要做相同的角度2. 请找到所求的快照邮递员: enter image description herePOST请求类型为“form-data”的身体参数不起作用+ angular 2

而且,找到我的非工作角码。什么是错的:

let formData: FormData = new FormData(); 
     formData.append('file', file); 
     formData.append('pid', 2); 
     formData.append('cid', 4); 
     let headers = new Headers(); 
     headers.append('Authorization', '5C7D01DD-95F5-44CA-B897-012B218D80012'); 
     let requestOptions = new RequestOptions({ headers: headers }); 
     console.log('API call: to upload lead file'); 
     return this.http.post("http://blahblha.com" + LeadApi, formData, requestOptions) 
      .retryWhen((error) => error.delay(this.appConfig.serviceCallRetryDelay)) 
      .timeout(this.appConfig.serviceCallRetryTimeOut) 
      .map((response: Response) => response.json()); 

I am getting Error 500- Internal Server Error 

此外,连接是从网络请求负载:

------WebKitFormBoundaryzbq2nbK8gMNeqBck 
Content-Disposition: form-data; name="file"; filename="Testleads.csv" 
Content-Type: application/vnd.ms-excel 


------WebKitFormBoundaryzbq2nbK8gMNeqBck 
Content-Disposition: form-data; name="pid" 

2 
------WebKitFormBoundaryzbq2nbK8gMNeqBck 
Content-Disposition: form-data; name="cid" 

4 
------WebKitFormBoundaryzbq2nbK8gMNeqBck-- 

我在做什么错在angular2?

+0

在当您尝试运行该控制台的任何错误? –

+0

您是否可以捕获您的网络和控制台选项卡 –

+0

您在响应中遇到什么错误? –

回答

0

首先创建一个Angular2服务,这样您就可以访问它并在需要获取或发布数据时调用方法。

服务:

@Injectable() 
export class ApiService { 
    private headers = new Headers({'Content-Type': 'application/form-data; charset=UTF-8'}); 

    constructor(private http: Http) { 
    } 

    public send(url, body: Object): Observable<any> { 
     let bodyString = this.serializeObj(body); 

     return this.http 
      .post(url, bodyString, {headers: this.headers}) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     let body = res.json(); 
     if (body) { 
      return body.data || body; 
     } else { 
      return {}; 
     } 
    } 

    private handleError(error: any) { 
     // In a real world app, we might use a remote logging infrastructure 
     // We'd also dig deeper into the error to get a better message 
     let errMsg = (error.message) ? error.message : 
      error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
     console.error(errMsg); // log to console instead 
     return Observable.throw(errMsg); 
    } 

    private serializeObj = function (obj, prefix = null) { 
     let str = [], p; 
     for (p in obj) { 
      if (obj.hasOwnProperty(p)) { 
       let k = prefix ? prefix + '[' + p + ']' : p, v = obj[p]; 
       str.push((v !== null && typeof v === 'object') ? 
        this.serializeObj(v, k) : 
        encodeURIComponent(k) + '=' + encodeURIComponent(v)); 
      } 
     } 
     return str.join('&'); 
    }; 
} 

在您的组件:

constructor(private apiService: ApiService) { 
    let mySendingObject = {}; // This is the object you send in your POST 
    this.sendData(mySendingObject); // And here we are actually calling our method that uses the post method within ApiService 
} 

sendData(myObj) { 
    let url = 'http://blahblha.com' + LeadApi; 
    return this.apiService.send(url, myObj); 
} 

,你需要把你的帖子,只是你的组件的方法sendData()内调用。

这种方式,你有几个一举两得的事情:

  • 您从您的应用程序的其余部分
  • 您可以创建一个更具体的服务,进口ApiService分开你的API服务。例如:UserService即进口和使用ApiService
  • 我们有一个方法:在通话
    • 处理错误:handleError()
    • 提取数据:extractData()
    • 对象序列:serializeObj()

结构应该是这样的:

  • ApiService:管理与Http(POST,GET等)
    • 本地服务,例如API调用:UserService:进口ApiService,有方法,如:updateUserdeleteUseraddUser ...对于例。
      • 的部件,例如:UsersViewComponent:使用UserService并通过视图与其互动。