2017-08-01 132 views
2

在angular 4中我使用了一个代码片段,例如:values.join不是文件中的函数http.es5.js Angular 4

let h = [{Content: 'application/json'}]; 

this.http.post(server, this.userDataObj, {headers: h})..... 

所以基本上我想在我的ajax调用中添加一个头文件。

现在,我不断收到一个错误

ERROR TypeError: values.join is not a function

我检查了错误的位置,我发现在文件http.es5.js有一个代码等;

req.headers.forEach(function (name, values) { 
     return xhr.setRequestHeader(name, values.join(',')); 
}); 

现在我加入了console.log(req.headers)只是片段上方,和我;

[Object] 
     0:Object 
     Content: 'application/json' 

现在据我知道在JS阵列forEach循环内部函数采用第二个参数(这是在http.es5.js值)是该元素的索引。我通过console.log(values)进行了测试,结果为0.因此,values.join不是函数,它永远不会是整数函数。

我试过了;

var headers = new Headers(); 
headers.append("Content", 'application/json'); 

this.http.post(server, this.userDataObj, {headers: headers}).subscribe(..... 

这也给我同样的错误。

试过这个;

var h = new Headers(); 
h.append("kkk", 'aaa'); 
let options = new RequestOptions({ headers: h }); 

this.http.post(server, this.userDataObj, options).subscribe(..... 

同样的错误。

这是一个错误?或者我犯了什么错误? 任何想法对我都很有帮助。 PS:我是Angular4的新手。

+0

标题不是数组。他们是'''RequestOptions'''对象。这个SO问题应该帮助https://stackoverflow.com/questions/41133705/how-to-correctly-set-http-request-header-in-angular-2 – Wainage

+0

我试过你提到的问题的接受答案,仍然是相同的错误。我现在试图提到的问题。请检查。我现在变得无能为力了。 :( –

回答

2

您需要使用angular/httpHeaders将标头添加到请求中。

第一次使用这些进口

import { Http, Headers} from '@angular/http'; 

然后添加标题这样

var headers = new Headers(); 

headers.append("Content", 'application/json'); 

this.http.post(server, this.userDataObj, {headers: headers }) 
+0

我也试过了,现在试过了,但是我得到的同样的错误。 –

4

角4.3:

import {HttpClient, HttpHeaders} from '@angular/common/http'; 
+0

创建头文件为... new HttpHeaders({'Content-Type':'application/json','content-language':' en'})。 –

-1
import { HttpClient, HttpHeaders } from '@angular/common/http'; 
import { Api } from '../../providers/providers'; 


export class demo{ 

    response: any;  

    constructor(public api: Api){ 
    this.apiCall(); 
    } 
    apiCall(){ 
    var headers = new HttpHeaders({ 
    'Content-Type': 'application/json', 
    'token': 'token_demo' 
     }); 

     this.response = this.api.post("services/user", {}, { headers: headers }); 
     this.response.subscribe((data) => { 
     console.log('data : ' + data); 
     }, err => { 
     console.error("error = ", err); 
     } 
    } 
} 

这是工作在... .....