angular cli http請求封裝+攔截器配置+ 接口配置文件


內容:接口配置文件、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的話就會自動跳轉到登錄頁面。

github: https://github.com/ft1107949255/BackSystem


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM