1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import { HttpClient } from '@angular/common/http';
import { Injectable, isDevMode } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { UtilService } from '@/services/util.service';
@Injectable() export class ApiService { async request(method, url, data = {}) { const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}`, }; const trim = s => s === undefined || s === null ? '' : s; const args = [ window['baseUrl'], url.replace(/:([^&;/?]+)/g, (...s) => trim(data[s[1]])), ].join('/');
const params = Object.keys(data).reduce((obj, key) => { obj[key] = trim(data[key]); return obj; }, {});
const optiOns= { observe: 'response' as 'response', // 获取完整响应对象 responseType: 'json' };
try { const requestData = { url: args, method: method, }; console.log(args);
const respOnse= await this.http[method](args, { ...options, headers, params }).toPromise(); console.log(response.headers); // 打印响应头 return response.body; } catch (e) { console.error(e); if (e.status !== 401) { // this.notify.create('error', `${e.status}`, e.error.message); } else { localStorage.clear(); this.util.navigate(['/user/login']); } throw e; } }
delete = (url) => (data?) => this.request('delete', url, data); get = (url) => (data?) => this.request('get', url, data); patch = (url) => (data?) => this.request('patch', url, data); post = (url) => (data?) => this.request('post', url, data); put = (url) => (data?) => this.request('put', url, data);
constructor( private http: HttpClient, private notify: NzNotificationService, private util: UtilService, ) { } } |