HTTP请求

  1. 设置后端地址已经静态资源地址
export const environment = {
  production: false,
  BASE_URL: 'http://10.61.177.108:8080',
  ASSETS_URL: '../assets/jsons'
};
  1. 设置请求的接口地址
export class WelcomeConstant {
    public static REG_FINGING_DETAILS = 'reg-fing-details.json';
}
  1. 拦截器
import { Injectable } from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse, HttpParams
} from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd/message';
const ignoreToken = ['user', 'evironment'];
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private nzMessageService: NzMessageService) {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>   {
       // console.log(req);
        // 补全地址
        let url = req.url;
        const needToken = ignoreToken.filter(u => url.match(u));
        console.log(needToken); // ['evironment']
        if (url.indexOf('http://') < 0 || url.indexOf('https://') < 0) {
            url = 'http://' + url;
            console.log(url); // http://../../../assets/json/evironment.details.json
        }
        // 设置token的请求头
        // 获取token值(可以从本地缓存里得到)
        const authToken = 'lvxinToken';
        if (authToken) {
            // 服务请求时所有的请求加入token
            const authReq = req.clone({
                headers: req.headers.set('Authorization', 'bearer' + authToken),
                url: req.url
            });
            // 服务器响应结果
            return next.handle(authReq).pipe(tap(event => {
                if (event instanceof HttpResponse) {
                    this.handleData(event);
                }
            }, error => {
                // token过期 服务器错误等处理
            }));
        }
        // 若token不存在,则不对请求进行处理
        return next.handle(req).pipe(tap(event => {
            if (event instanceof HttpResponse) {
                // console.log(event);
                this.handleData(event);
            }
        }, error => {
            // token过期 服务器错误等处理
        }));
    }
    public handleData(event: HttpResponse<any> | HttpErrorResponse): any {
            // 业务处理:一些通用操作
            switch (event.status) {
                case 200:
                    if (event instanceof HttpResponse) {
                        const body: any = event.body;
                        console.log(event);
                        this.createMessage('success')
                    }
                    break;
                case 401: // 未登录状态码
                    // this.goTo('/login');
                    break;
                case 404:
                    console.log(event);
                    this.createMessage('warning');
                    break;
                case 500:
                    console.log(event);
                    console.log(event);
                    this.createMessage('error')
                    break;
                default:
                    return of(event);
            }
    }
    createMessage(type: string): void {
        this.nzMessageService.create(type, `This is a message of ${type}`);
    }
}


3.1注入

 providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
  ],
  1. 写get, post, put, delete请求后端服务

4.1 必须现引用

private http: HttpClient

4.2 get

getRegFingingDetails() {
  return this.http.get(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`)
  .pipe(
    catchError(this.helperService.handleError)
    )
}

4.3 post

getRegFingingDetailsPost(params:any) {
  return this.http.post(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`, params)
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

HTTP请求
HTTP请求

4.4 put

getRegFingingDetailsPut(params:any) {
  return this.http.post(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`, params)
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

HTTP请求

HTTP请求

4.5 delete

getRegFingingDetailsDelete(params:any) {
  return this.http.delete(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}/${params.id}`,)
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

HTTP请求

4.6 error

getRegFingingDetails() {
  return this.http.get(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`)
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

4.7 设置请求头

setHttpOptions (params:any) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      Authorization: 'my-auth-token'
    }), 
  };
  return this.http.get(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`, httpOptions)
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

4.8 请求文件类型的参数

getFileType (params:any) {
  return this.http.get(`${environment.ASSETS_URL}/${WelcomeConstant.REG_FINGING_DETAILS}`, {responseType: 'blob'})
  .pipe(
    catchError((error => {return throwError({errorMessage: 'test error http'})}))
    )
}

5.handleError

public handleError(error: HttpErrorResponse) {
  if (error.status === 0) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong.
    console.error(
      `Backend returned code ${error.status}, body was: `, error.error);
  }
  // Return an observable with a user-facing error message.
  return throwError(
    'Something bad happened; please try again later.');
  } 
上一篇:打包mysql、tomcat、jdk为一个软件


下一篇:PageOffice在前后端分离(如:Vue)中调用示例 前端使用vue集成pageoffice