在http get请求中正确的Angular 5传递标头 [英] Angular 5 pass headers properly in http get requests
问题描述
所以最初我是对我的api请求使用不推荐使用的HttpModule,但是现在我正在使用HttpClientModule,并且在正确传递标头方面存在问题.我有一个调用api来获取一些数据的函数...这就是我最初使用HttpModule的目的
so initially i was using the deprecated HttpModule for my api requests but i'm using the HttpClientModule now and having issues with passing headers correctly. i've got a function that calls api to get some data...this is what i had initially with HttpModule
service.ts
service.ts
export class userService {
//using HttpModule
getCurrentProfile() {
let v = this.page_header();
return this.http.get(this.userProfileUrl, {headers: headers})
.toPromise()
.then(response => response.json())
.catch(this.handleError);
};
//using HttpClientModule
getCurrentProfile() {
let headers = new HttpHeaders();
return this.http.get(this.userProfileUrl, {headers: headers})
.toPromise()
.then(response => response.json())
.catch(this.handleError);
};
private page_header() {
let data = localStorage.getItem('auth_token');
let headers = new Headers();
let opt: RequestOptions;
headers.append('Authorization', 'JWT ' + data);
opt = new RequestOptions({ headers: headers });
return opt;
}
}
component.ts
component.ts
getStoreProfile() {
//using HttpModule
this.userSrv.getCurrentProfile().then(response => {
localStorage.setItem('store', JSON.stringify(response));
this.profile = JSON.parse(localStorage.getItem('store'));
}).catch(err => this.error = err)
//using HttpClientModule
this.userSrv.getCurrentProfile().subscribe(res => {
let data = res;
localStorage.setItem('store', JSON.stringify(res));
this.profile = JSON.parse(localStorage.getItem('store'));
})
} 所以initailly都可以与HttpModule一起使用,但是现在与HttpClientModule一起我会出错
} So initailly it all worked with HttpModule but now with HttpClientModule i get errro
detail:"Authentication credentials were not provided."
我如何使用HttpClientModule正确传递标头.
How am i to pass headers correctly using HttpClientModule.
推荐答案
详细信息:未提供身份验证凭据."
detail:"Authentication credentials were not provided."
由于标题为空,因此出现此问题.
You are getting this issue because your header is empty.
使用httpOptions
对象发送标头
在新的HttpClientModule
中,JSON是假定的默认值,不再需要使用res.json()
进行显式解析.
建议在promises
上使用observables
.通过转换为Promise,您将失去取消请求的能力和链接RxJS运算符的能力.
use httpOptions
object to send header
In new HttpClientModule
JSON is an assumed default and no longer needs to be explicitly parsed using res.json()
it's recommended to use observables
over promises
. By converting to a promise you will lose the ability to cancel a request and the ability to chain RxJS operators.
getCurrentProfile():Observable<any> {
let data = localStorage.getItem('auth_token');
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ' 'JWT ' + data'
})
};
return this.http.get(this.userProfileUrl, httpOptions)
.catch(this.handleError);
};
这篇关于在http get请求中正确的Angular 5传递标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!