angular2--前端对接接口方法

angular2前端对接接口方法

1、需要将谷歌浏览器设置跨域
在这里插入图片描述
https://www.cnblogs.com/cshi/p/5660039.html

2、在 \src\services\httpService.ts中创建接口路径:
post 方法:

public UserRegister(params:any):Promise{
    return this.http.post(this.urlBasePath+"/api.php?ac=user_register",params)
              .toPromise()
              .then(this.extractData)
              .catch(this.handleError);
}

get 方法:

public UserRegister(params:any):Promise{
    return this.http.post(this.urlBasePath+"/api.php?ac=user_register&telephone="+params.telephone+"&password="+params.password+"&code="+params.code)
              .toPromise()
              .then(this.extractData)
              .catch(this.handleError);
}

3、在需要调用接口的页面内(例:注册页面 regpage.ts)
a、//loading弹窗显示 this.httpService.showModal();
b、需要用到的参数:

let params={
		telephone:this.phoneNumber,
		password:this.password,
		code:this.code
}

c、发送请求

this.httpService.UserRegister(params).then(result => {
	//这里写请求成功的方法
	this.httpService.hideModal();//关闭loading窗口
	if(result.code=="FAILED"){
		Commons.showToast(result.msg);
	}else{
		this.httpService.showDialog(EditStatus, {data: {status: 'reg'}});
		this.settingService.SettingValue('userInfo',result.data)
	}
},error=>{
	//这里写请求失败的方法
	this.httpService.hideModal();//关闭loading窗口
	Commons.showToast("请求失败,请重试!");	
})

d、补充几个公用方法

Toast弹窗 Commons.showToast("请求失败,请重试!");	
Alert 弹窗Commons.showAlert("请求失败,请重试!");

存储全局变量

this.settingService.SettingValue('userInfo',result.data);

获取全局变量

this.settingService.GettingValue('userInfo');

4、完整例子:
httpService.ts:

	/**
     *	获取首页轮播图
     */
    public getBanner(params:any):Promise<any>{
        return this.http.post(this.urlBasePath+"/api.php?ac=index_getBanner",params)
                  .toPromise()
                  .then(this.extractData)
                  .catch(this.handleError);
    }

homePage.ts:

constructor(private navigator: OnsNavigator,
		private httpService: HttpService,
		private eventBus: EventServices,
		private settingService: SettingService) {
			this.getBanner();
	}
//获取首页轮播图
	getBanner() {
		let params = {}
		this.httpService.getBanner(params).then(result => {
			if(result.code == "FAILED") {
				Commons.showToast(result.msg);
			} else {
				console.log('测试')
			}
		}, error => {
	
		})
	}

你可能感兴趣的:(angular2--前端对接接口方法)