/project_name/src/providers/rest/rest.tsrest.ts
"""
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class RestProvider {
constructor(public http: Http) {
//console.log('Hello RestProvider Provider');
}
// 登录url
private apiUrlLogin ='http://127.0.0.1:5000/api/login';
// 获取用户信息url
private apiUrlUserInfo ='http://127.0.0.1:5000/api/get_user_info';
// 登录
login(mobile, password): Observable {
let pramas = JSON.stringify({
"telephone": mobile,
"password": password,
});
return this.postUrlReturn(this.apiUrlLogin, pramas)
}
// 获取用户信息
getUserInfo(userId): Observable {
return this.getUrlReturn(this.apiUrlUserInfo +"?userid=" + userId);
}
// 全局获取 HTTP 请求的方法
// get方法
private getUrlReturn(url:string): Observable {
return this.http.get(url)
.map(this.extractData)
.catch(this.handleError);
}
// post方法
private postUrlReturn(url:string, pramas:string): Observable {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options =new RequestOptions({
headers: headers
});
return this.http.post(url, pramas, options)
.map(this.extractData)
.catch(this.handleError);
}
// 处理接口返回的数据,处理成 json 格式
private extractData(res: Response) {
let body = res.json();
return JSON.parse(JSON.stringify(body)) || {};
}
// 处理请求中的错误,考虑了各种情况的错误处理并在 console 中显示 error
private handleError(error: Response |any) {
let errMsg:string;
if (errorinstanceof 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);
}
}
参考资料
Ionic3 前端JS发送post请求部分