在使用angular时,接触最频繁的是http请求,
一、不用考虑请求中含token的情况
(1)get方式的请求如下:
先配置header
this.httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json'
})};
再进行请求
this.http.get(this.path,this.httpOptions)
.subscribe(data => {
//数据赋值,将所有数据都安置到对应的框中
var obj = eval("data"); //序列化代码
},error => {
console.log(error);
});
(2)post方式的请求
private encodeHttpParams(params: any): any {
if (!params) return null;
return new HttpParams({fromObject: params});
}
login() {
if (this.username == "" || this.password == " ") return false;
var params = {
username: this.username,
password: this.password,
};
this.http.post(this.path, this.encodeHttpParams(params))
.subscribe(res => {
//成功收到response
//1、获取post请求返回的信息
var obj = eval("res");
if(obj.access_token){
//2、保存获取的有效token和更新的token
window.localStorage.removeItem("access_token");
window.localStorage.setItem("access_token",obj.access_token);
window.localStorage.removeItem("refresh_token");
window.localStorage.setItem("refresh_token",obj.refresh_token);
//3、设置根页面为TabsPage页
this.navCtrl.setRoot(TabsPage);
}else{
alert("登录失败!");
}
// console.log(res);
}, error => {
// 请求发生错误
console.log(error);
alert("登录失败!");
}
);
}
二、考虑token存在的方式
这里的访问需要在请求头中配置Authorization一项
请求头的配置如下:
this.httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
"Authorization": '自己选' + 获取的token
})};
get()方法同一一样,只是headers的内容多了一项
post单独使用的方法如下:(变化也不大,只是这种和一中略微不同)
this.http.post(Url, '{}',this.httpOptions).subscribe(
(data) => {
var obj = eval("data");
});
本文介绍了在Ionic3中如何使用HttpClient进行数据请求,包括无token情况下的GET和POST请求,以及处理包含token的请求头配置方法。
3386

被折叠的 条评论
为什么被折叠?



