Angular http服务工具类
Angular http服务工具类大致可以分为两个版本,一个是Angular4.3之前位于@angular/http下的Http服务,另一个是Angular4.3之后位于@angular/common/http下HttpClient服务。具体区别可查看https://www.cnblogs.com/54hsh/p/11490711.html
1、Angular4.3之前@angular/http下的Http服务工具类
import { Injectable } from "@angular/core";
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
const options = new RequestOptions({
withCredentials: true,
headers: new Headers({ 'X-Requested-With': 'XMLHttpRequest' })
});
@Injectable()
export class HttpUtil {
private baseUrl: any;
constructor(private http: Http) {
this.baseUrl = 'http://localhost:8080';
}
get(url: string) {
console.log('发送get请求,url:', url)
url = this.baseUrl + url;
return this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError);
}
post(url: string, params?: any) {
console.log('发送post请求,url:', url, ',params:', params);
url = this.baseUrl + url;
return this.http.post(url, params, options)
.map(this.extractData)
.catch(this.handleError);
}
put(url: string, params?: any) {
console.log('发送put请求,url:', url, ',params:', params);
url = this.baseUrl + url;
return this.http.put(url, params, options)
.map(this.extractData)
.catch(this.handleError);
}
delete(url: string) {
console.log('发送delete请求,url:', url);
url = this.baseUrl + url;
return this.http.delete(url, options)
.map(this.extractData)
.catch(this.handleError);
}
postForm(url: string, params?: any) {
let formData: FormData = new FormData();
formData.append('username', params.username);
formData.append('password', params.password);
return this.post(url, formData);
}
private extractData(response: Response) {
console.log('提取数据:', response);
let body = response.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error('异常信息:', errMsg);
return Observable.throw(errMsg);
}
}
2、Angular4.3之后@angular/common/http下的HttpClient服务工具类
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
const options = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
}
@Injectable()
export class HttpClientUtil {
private baseUrl: any;
constructor(private httpClient: HttpClient) {
this.baseUrl = 'http://localhost:8080';
}
public get(url: string) {
console.log('发送get请求,url:', url);
url = this.baseUrl + url;
return this.httpClient.get(url, options)
.pipe(map(this.extractData), catchError(this.handleError));
}
public post(url: string, params?: any) {
console.log('发送post请求,url:', url, ',params:', params);
url = this.baseUrl + url;
return this.httpClient.post(url, params, options)
.pipe(map(this.extractData), catchError(this.handleError));
}
public put(url: string, params?: any) {
console.log('发送put请求,url:', url, ',params:', params);
url = this.baseUrl + url;
return this.httpClient.put(url, params, options)
.pipe(map(this.extractData), catchError(this.handleError));
}
public delete(url: string) {
console.log('发送delete请求,url:', url);
url = this.baseUrl + url;
return this.httpClient.delete(url, options)
.pipe(map(this.extractData), catchError(this.handleError));
}
postForm(url: string, params?: any) {
let formData: FormData = new FormData();
formData.append('username', params.username);
formData.append('password', params.password);
return this.post(url, formData);
}
private extractData(response: Response) {
console.log('提取数据:', response);
let data = response.json();
return data || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const data = error.json() || '';
const err = data.toString || JSON.stringify(data);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error('异常处理:', errMsg);
return Observable.throw(errMsg);
}
}
千万不要试图去研究 研究了很久都整不明白的东西,或许是层次不到,境界未到,也或许是从未在实际的应用场景接触过,这种情况下去研究,只会事倍功半,徒劳一番罢了。能做的就是不断的沉淀知识,保持一颗积极向上的学习心态,相信终有一天所有的困难都会迎刃而解。