ionic3中用HttpClient方式进行请求数据

本文介绍了在Ionic3中如何使用HttpClient进行数据请求,包括无token情况下的GET和POST请求,以及处理包含token的请求头配置方法。

在使用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");
        
      });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值