ionic4 angular 数据请求方式httpServices 拦截器

项目GItHub https分支

1.这里提供统一拦截后端接口数据处理,api统一文件管理方式:

统一拦截如下

// 目录src/service/request.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { LoadingController, AlertController } from '@ionic/angular';
import { Observable  } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class RequestService {

  constructor(private httpClient: HttpClient, private loading: LoadingController,public alertController: AlertController) { }

  headerOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token'
    }),
  }

  public request (method:string,url:string,data: Object):Observable> {
    this.loadShow()
    return this.httpClient.request(method,url,{ ...data, ...this.headerOptions, ...{observe: 'response'}}).pipe(
      tap((response) => {
        this.handleSuccess(response)
      },
      (error) => {
        this.handleError(error)
      }),
      finalize(() => {
        this.loadHide()
      })
  )
  }

  private handleSuccess(response) {
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
    } else {
      if (error.status === 400) {
        this.alert('请求失败')
      } else if (error.status === 404) {
        this.alert('参数有误,请检查')
      } else if (error.status === 500) {
        this.alert('接口有错,联系后台管理员')
      } else {
        this.alert(error.message)
      }
    }
  }

  private async alert(message) {
    const alert = await this.alertController.create({
      header: '提示',
      message,
      buttons: ['确认']
    });
    await alert.present();
  }

  private async loadShow() {
    const loading = await this.loading.create({
      message: '加载中...',
      duration: 2000,
      translucent: true,
      cssClass: 'custom-class custom-loading'
    });
    await loading.present();
  }

  private async loadHide() {
    await this.loading.dismiss()
  }

}

2. 统一管理api

// 目录src/api/api.ts
import { Injectable } from '@angular/core';
import { RequestService } from 'src/service/request.service'
import { Observable  } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class test {
  constructor(public requestService: RequestService){}

  public login (data: any) {
    return this.requestService.request(
      'get',
      'https://api.apiopen.top/getJoke',
      {params: data}
    )
  }
}

3.调用

目录/src/pages/tab1/tab1-page.ts
import { Component } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import {HttpServiceService} from 'src/service/http-service.service'
import { test } from 'src/api/api'
import { Observable, from } from 'rxjs';



@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json;application/x-www-form-urlencodeed; charset=utf-8', "Referer": "https://www.aganchina.cn" })
  };

  constructor(private test: test, private httpClient: HttpClient, private router: Router,private httpService: HttpServiceService) { }

  goDetails() {
    this.test.login({page:1,count:2,type: 'video'}).subscribe(res => {
      console.log(res)
    })
  }
}

你可能感兴趣的:(ionic4 angular 数据请求方式httpServices 拦截器)