在Angular 4中将标头添加到http.get时出错

时间:2018-07-17 13:20:15

标签: angular typescript angular2-services angular4-httpclient

我正在尝试以下代码:

  let myHeader = new HttpHeaders();
    myHeader.append("Authorization", Token);
    return this.http
      .get(this.service.GetDomainPrefix() + "Source/Download/" + id, 
        {       
          headers: myHeader, responseType: ResponseContentType.Blob
    }).map(res => {
    return {
      filename: name + '.mp4',
      data: res.blob()
    };
  })

但出现以下错误:

  

类型'{header:HttpHeaders; responseType:   无法将ResponseContentType.Blobl;}'分配给类型为参数的参数   'RequestOptionsArgs'。类型'HttpHeaders'不可分配给类型   “标题”

问题仅在于标题,因为没有标题就没有错误。 如何在获取请求中添加头像?

3 个答案:

答案 0 :(得分:1)

这可能是因为您使用的是HttpModule(角度2,4),而不是新的HttpClientModule(角度4,5,6) (以及Http类而不是HttpClient类)

此外,HttpHeaders是不可变的。要使用新的HttpClientModule,请使用以下代码

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

constructor(private http: HttpClient){}
//...
let myHeader = new HttpHeaders().append("Authorization", Token);
    return this.http
      .get(this.service.GetDomainPrefix() + "Source/Download/" + id, 
        {       
          headers: myHeader, responseType: 'blob'
    })
.map(res =>  {
      filename: name + '.mp4',
      data: res
          })

您需要修改AppModule来导入HttpClientModule而不是HttpClient

答案 1 :(得分:0)

import {Headers} from 'angular2/http'; var headers = new Headers();

这是您应该使用的。它是用错误的简单语言写的,即不能分配给HttpHeaders()类型。您必须使用Headers()

答案 2 :(得分:0)

// HttpClient(@ angular / common / http)

let myHeader = new HttpHeaders();
    myHeader.append("Authorization", Token);
let options =  {       
          headers: myHeader, responseType: 'blob'
    }

// Http(@ angular / http)

 let myHeader = new Headers();
    myHeader.append("Authorization", Token);

let options = new RequestOptions() {       
          headers: myHeader, responseType: ResponseContentType.Blob
    }

//请求

return this.http
      .get(this.service.GetDomainPrefix() + "Source/Download/" + id, options).map(res => {
    return {
      filename: name + '.mp4',
      data: res.blob()
    };
  })