Angular 4 RequestOption对象不能为post方法分配

我对这些代码有困难,我创建了一个包含以下代码块的标头

headers.append("Authorization",btoa(username+":"+password));

var requestOptions = new RequestOptions({headers:headers});

但是,如果我尝试在post方法中使用它

return this.http.post(url,JSON.stringify({username,password}),requestOptions)
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

我收到此错误消息

Typescript Error
Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'. Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'. Index signature is missing in type 'Headers'.

我尝试将Header()更改为HttpHeader(),但它没有帮助.问题是什么?

更新

删除了requestOptions对象,然后我从HttpHeaders()创建了头文件

let headers = new HttpHeaders();

并在post方法中使用此标头值

return this.http.post(url,{ options: { headers: headers; } })
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

然后得到这个错误

[ts]
Argument of type '{ options: { headers: HttpHeaders; }; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Object literal may only specify kNown properties,and 'options' does not exist in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

我也尝试过这个

return this.http.post(url,{ headers: headers })
    .map(res=>res.json())
    .map(res=>{
      if(res){
        localStorage.setItem("isLogged",res);
        this.loggedIn =true;
      }
      return res;
    });

然后我在第一个“.map”上收到错误

[ts] Property 'map' does not exist on type 'Observable<Object>'.

解决方法

RequestOptions类将与不推荐使用的 Http模块一起使用,因为您收到此错误,我假设您正在使用 HttpClient模块.

如果你想通过代码显示的选项设置标题,你可以使用类似的东西(Angular docs显示的简化版本):

request(url,{ body },{ options: { headers?: HttpHeaders; } })

但是,您也可以直接设置标题,而无需使用选项.这看起来像这样:

request(url,{ headers?: HttpHeaders; } )

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...