最近在项目中折腾了下angular2,所以出来跟大家分享,希望有帮助,每个公司业务不一样,按实际情况而定,个人学习心得,不作为标准。
1、定义http-interceptor.service.ts服务,统一处理http请求
export class HttpInterceptorService {
constructor(private http: Http) {
}
/**
- 统一发送请求
- @param params
- @returns {Promise<{success: boolean,msg: string}>|Promise
}
*/
public request(params: any): any {
if (params['method'] == 'post' || params['method'] == 'POST') {
return this.post(params['url'],params['data']);
}
else {
return this.get(params['url'],params['data']);
}
}
/**
- get请求
- @param url 接口地址
- @param params 参数
- @returns {Promise
|Promise}
*/
public get(url: string,params: any): any {
return this.http.get(url,{search: params})
.toPromise()
.then(this.handleSuccess)
.catch(res => this.handleError(res));
}
/**
- post请求
- @param url 接口地址
- @param params 参数
- @returns {Promise
|Promise}
*/
public post(url: string,params: any) {
return this.http.post(url,params)
.toPromise()
.then(this.handleSuccess)
.catch(res => this.handleError(res));
}
/**
- 处理请求成功
- @param res
- @returns {{data: (string|null|((node:any)=>any)
*/
private handleSuccess(res: Response) {
let body = res["_body"];
if (body) {
return {
data: res.json().content || {},page: res.json().page || {},statusText: res.statusText,status: res.status,success: true
}
}
else {
return {
statusText: res.statusText,success: true
}
}
}
/**
- 处理请求错误
- @param error
- @returns {void|Promise
|Promise |any}
*/
private handleError(error) {
console.log(error);
let msg = '请求失败';
if (error.status == 400) {
console.log('请求参数正确');
}
if (error.status == 404) {
console.error('请检查路径是否正确');
}
if (error.status == 500) {
console.error('请求的服务器错误');
}
console.log(error);
return {success: false,msg: msg};
}
}
2、在每一个模块创建一个service,service定义此模块的所有http数据请求,我这里演示登录模块:login.service.ts
import {HttpInterceptorService} from 'app/commons/service/http-interceptor.service'
@Injectable()
export class LoginService {
constructor(private httpInterceptorService: HttpInterceptorService) {
}
/**
- 登陆功能
- @param params
- @returns {Promise<{}>}
*/
login(userName: string,passWord: string) {
return this.httpInterceptorService.request({
method: 'POST',url: 'http://119.232.19.182:8090/login',data: {
loginName: userName,password: passWord
},});
}
/**
- 注册
- @param user
- @returns {any}
*/
reguster(user: any) {
return this.httpInterceptorService.request({
method: 'POST',url: 'http://119.232.19.182:8090/reguster',data: {
user: user
},});
}
}
3、在component注入servicelogin.service.ts。调用seriveLogin.service.ts服务定义的方法,这里通过login.component.ts演示
selector: 'login',templateUrl: './login.component.html',providers: [LoginService],})
export class LoginComponent {
private userName: string;
private passWord: string;
constructor(private loginService: LoginService) {
}
/**
- 登录
*/
toLogin() {
this.loginService.login(this.userName,this.passWord).then(result => {
console.log(result);//打印返回的数据
});
}
}