【问题标题】:How to pass custom data in headers in angular 4如何在角度4的标题中传递自定义数据
【发布时间】:2018-06-27 03:31:46
【问题描述】:

这是我的提供程序代码,其中我在标头中传递多个数据

  postEventComment(body,headers){
      return this.http.post(this.api_comment_event, body,{ headers: {'Content-Type' :'multipart/form-data','userId':'1451'} })
      .do((res: Response) => console.log(res))
      // .map((res: Response) => res.json())
      .catch(this.catchError)
      }

这是我的评论ts代码

this.body2 = 'eventId' + '=' + id + '&comment=' + this.body.comment  
let headers = new Headers();
let body = this.body
this.api_list.postEventComment(this.body2,headers).subscribe(data =>  {
console.log(data);});

下面是我的截图

【问题讨论】:

  • this.http的类型是什么?请提供您的问题的最低限度的复制品

标签: angular typescript ionic3


【解决方案1】:

你应该使用这样的东西。

代码

this.body2 = 'eventId' + '=' + id + '&comment=' + this.body.comment  
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('userId', 123);
let opts = new RequestOptions();
opts.headers = headers;
this.api_list.postEventComment(this.body2 , opts).subscribe(data =>  {
console.log(data);});

【讨论】:

  • ERROR TypeError: Cannot set property 'headers' of undefined(...)
【解决方案2】:

在您的情况下,根据您的 API,您在错误的地方使用了 userId。取而代之的是,您应该传递身份验证令牌。解决方案主要取决于您使用的 API。

顺便说一句,你可以使用这样的标题:

const headers: Headers = new Headers({
  'Content-Type': 'multipart/form-data',
  'userId': '123'
});

然后像这样将它传递给你的发布请求:

this.http.post(this.api_comment_event, body,{ headers: headers })

别忘了导入标头:

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

如果可能,请分享 API 详细信息以获得更准确的答案。

【讨论】:

    【解决方案3】:

    以下是问题的详细答案:

    从 Angular 端将数据传递到 HTTP 标头(首选版本 >= angular 4)

    我们可以将数据传递到标头中的方法不止一种。 语法不同,但意思都一样。

    // Option 1 
     const httpOptions = {
       headers: new HttpHeaders({
         'ID': emp.UserID,
       })
     };
    
    
    // Option 2
    
    let httpHeaders = new HttpHeaders();
    httpHeaders = httpHeaders.append('ID', '001');
    
    let options = {headers:httpHeaders};
    
    
    // Option 1 Call the Web API Url.
       return this.http.post(this.url + 'testMethod', body,httpOptions)
    
    // Option 2 Call the Web API Url.
       return this.http.post(this.url + 'testMethod', body,options)
    

    在调用中,您可以找到作为标题传递的字段,如下图所示(在浏览器中转到网络选项卡):

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多