微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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; } )

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐