gpt4 book ai didi

Angular 4 RequestOption 对象不可分配给 post 方法

转载 作者:太空狗 更新时间:2023-10-29 17:24:37 25 4
gpt4 key购买 nike

我对这些代码有问题,我用下面的代码块创建了一个标题

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() 创建了 header

let headers = new HttpHeaders();

并在其中的 post 方法中使用此 header 值

return this.http.post(url,JSON.stringify({username,password}), { 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,JSON.stringify({username,password}), { 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>'.

最佳答案

@angular/http 已弃用

改用@angular/common/http

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

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};


addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}

关于Angular 4 RequestOption 对象不可分配给 post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47894300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com