当前位置: 移动技术网 > IT编程>开发语言>JavaScript > angular cli http请求封装+拦截器配置+ 接口配置文件

angular cli http请求封装+拦截器配置+ 接口配置文件

2019年06月19日  | 移动技术网IT编程  | 我要评论

内容:接口配置文件、http请求封装 、拦截器验证登录

1、接口配置文件

app.api.ts

import { component, oninit } from '@angular/core';
/**
 * 接口配置文件
 * baseurl
 * urllist
 */
export class apilist implements oninit {
  baseurl: any = '';
  urllist: any = {};
  constructor() { 
    this.baseurl = 'http://127.0.0.1';
    this.urllist =  {
      'login': {
        path: '/login',
        params: {
          username: '',
          password: ''
        }
      },
      'getuser': {
        path: '/getuser',
        params: {
          id: ''
        }
      }
    }
  }
  ngoninit() {}
}

上面模拟定义了两个接口

2、http请求封装

app.service.ts

 

import { component, injectable } from '@angular/core';
import { httpclient, httpparams } from '@angular/common/http';
import {apilist} from './app.api';  // 引入api配置文件

@component({
  providers:[apilist]
})

@injectable()
export class selfhttp {
  public restserver;
  public http;
  status = {
    '0': '请求超时,请检查网络是否断开或者链接是否正确',
    "400": "错误的请求。由于语法错误,该请求无法完成。",
    "401": "未经授权。服务器拒绝响应。",
    "403": "已禁止。服务器拒绝响应。",
    "404": "未找到。无法找到请求的位置。",
    "405": "方法不被允许。使用该位置不支持的请求方法进行了请求。",
    "406": "不可接受。服务器只生成客户端不接受的响应。",
    "407": "需要代理身份验证。客户端必须先使用代理对自身进行身份验证。",
    "408": "请求超时。等待请求的服务器超时。",
    "409": "冲突。由于请求中的冲突,无法完成该请求。",
    "410": "过期。请求页不再可用。",
    "411": "长度必需。未定义“内容长度”。",
    "412": "前提条件不满足。请求中给定的前提条件由服务器评估为 false。",
    "413": "请求实体太大。服务器不会接受请求,因为请求实体太大。",
    "414": "请求 uri 太长。服务器不会接受该请求,因为 url 太长。",
    "415": "不支持的媒体类型。服务器不会接受该请求,因为媒体类型不受支持。",
    "416": "http 状态代码 {0}",
    "500": "内部服务器错误。",
    "501": "未实现。服务器不识别该请求方法,或者服务器没有能力完成请求。",
    "503": "服务不可用。服务器当前不可用(过载或故障)。"
  };

  constructor(http: httpclient, public api: apilist) {
    console.log(this.api.baseurl);
    this.http = http;
    this.restserver = this.api.baseurl;
  }

  public get(url, params?: object, cb?: function) {
    this.msg(url);
    let httpparams = new httpparams();
    const vm = this;
    if (params) {
      for (const key in params) {
        if (params[key] === false || params[key]) {
          httpparams = httpparams.set(key, params[key]);
        }
      }
    }
    vm.http.get(vm.restserver + url, { params: httpparams })
      .subscribe(data => {
        cb(data);
      },(err)=>{
        console.log(this.status[err.status]);
      });
  }

  public post(url, data?: object, cb?: function, options?: object) {
    this.msg(url);
    const vm = this;
    vm.http.post(vm.restserver + url, data, options)
      .subscribe(res => {
        cb(res);
      }, (err) => {
        console.log(err);
        console.log(this.status[err.status]);
       }, () => {
         //...请求完成
       }
      );
  }

  public put(url, data?: object, cb?: function, options?: object) {
    this.msg(url);
    const vm = this;
    vm.http.put(vm.restserver + url, data, options)
      .subscribe(res => {
        cb(res);
      },(err)=>{
        console.log(this.status[err.status]);
      });
  }

  public delete(url, params?: object, cb?: function) {
    this.msg(url);
    let httpparams = new httpparams();
    const vm = this;
    if (params) {
      for (const key in params) {
        if (params[key]) {
          httpparams = httpparams.set(key, params[key]);
        }
      }
    }
    vm.http.delete(vm.restserver + url, { params: httpparams })
      .subscribe(data => {
        cb(data);
      },(err)=>{
        console.log(this.status[err.status]);
      });
  }
  public msg(url) {
    console.log('/*')
    console.log(' **开始请求',url)
    console.log(' */')
  }
}

 

上面定义了几个请求的函数,已经提示信息的函数。

app.module.ts注入

 

import {apilist} from './common/app.api';
.
.
..
providers: [httpinterceptorproviders, apilist],

 

example.ts

 

import { component, oninit } from '@angular/core';
import { httpheaders } from '@angular/common/http';
import { selfhttp } from 'src/app/common/app.service';
import {apilist} from '../common/app.api';  // 引入
@component({
  selector: 'app-article',
  templateurl: './article.component.html',
  styleurls: ['./article.component.css'],
  providers:[selfhttp, apilist]
})
export class articlecomponent implements oninit {
  httpoptions = {
    headers: new httpheaders({
      'content-type': 'application/json',
      'authorization': 'my-auth-token'
    })
  };
  data: any;
  constructor(public http: selfhttp, public api: apilist) {
    console.log(this.api);
  }

  ngoninit() {
    this.http.post(this.api.urllist.login.path, {username: 1, password:22, other:1113}, res => {
      console.log('结果', res);
    }, this.httpoptions);

  }
}

然后访问的话就会

 

2、拦截器

app.myintercept.ts

 

/**
 * 拦截器验证token
 */
import { injectable } from '@angular/core';
import {httpinterceptor, httphandler, httprequest, httpevent,} from '@angular/common/http';
import { router } from '@angular/router';
import { observable,  } from 'rxjs';
import {apilist} from './app.api'

@injectable()
export class interceptorservice implements httpinterceptor {
    
    constructor( public router: router,  public api: apilist) { 
        // localstorage.setitem('access_token', 'xxxxxxxxxxxxx')
    };
    intercept(req: httprequest<any>, next: httphandler): observable<httpevent<any>> {
        let authreq: any;
        // 实现第一次不拦截的方式:1. 指定接口不拦截  2. 判断本地localstorage
        let loginurl = this.api.baseurl + this.api.urllist['login']['path'];
        if (req.url !== loginurl) {
            if (localstorage.getitem('access_token')) {
                // console.log(2);
                const token = localstorage.getitem('access_token');
                authreq = req.clone({ setheaders: { token } });
                return next.handle(authreq);
            } else {
                // 未登录  ==  access_token
                this.router.navigate(['/login']);
            }
        }
        authreq = req.clone({ setheaders: {} });
        return next.handle(authreq);
    }
    
}

 

 

 

上面请求会验证是否有token,没有就跳转到登录页面。

定义拦截器收集文件

http-intercepts/index.ts

/**
 * 拦截器 收集
 * barrel
 */
import { http_interceptors } from '@angular/common/http';
import { interceptorservice } from '../app.myintercept';

export const httpinterceptorproviders = [
    { provide: http_interceptors, useclass: interceptorservice, multi: true },
];

app.module.ts注入

import {httpinterceptorproviders} from 'src/app/common/http-interceptors/index'
.
.
.
.
providers: [httpinterceptorproviders, apilist],

现在如果进入页面请求,没有带token的话就会自动跳转到登录页面。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网