Commit d75d942f authored by 范雪寒's avatar 范雪寒

refactor: 网络部分抽到基类里

parent 5c583207
This diff is collapsed.
{
"ver": "1.0.8",
"uuid": "971c9f08-044e-439b-8d32-e6b76be34717",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
\ No newline at end of file
export class middleLayerBase extends cc.Component { export class middleLayerBase extends cc.Component {
callNetworkApiPost(uri, data, callBack) {
this.getBaseUrl((baseUrl) => {
const xhr = new XMLHttpRequest();
const url = `${baseUrl}${uri}`;
xhr.open("POST", url, true);
xhr.setRequestHeader('content-type', 'application/json');
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
callBack(JSON.parse(xhr.responseText));
}
}
xhr.send(JSON.stringify(data));
});
}
callNetworkApiGet(uri, data, callBack) {
this.getBaseUrl((baseUrl) => {
let queryStr = '?';
const params = [];
for (const key in data) {
if (Object.hasOwnProperty.call(data, key)) {
params.push(`${key}=${data[key]}`);
}
}
queryStr += params.join("&");
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
callBack(xhr.responseText);
}
};
const url = `${baseUrl}${uri}${queryStr}`;
console.log('url = ' + url);
xhr.open('GET', url, true);
xhr.send();
});
}
async getBaseUrl(callback) {
const engineInfo = await this.getEngineInfo();
const { isDev } = JSON.parse(engineInfo);
if (isDev == 1) {
callback('http://staging-openapi.iteachabc.com');
} else {
callback('http://openapi.iteachabc.com');
}
}
getEngineInfo() {
if ((<any>window).air.engineInfo) {
return (<any>window).air.engineInfo;
} else {
return new Promise((resolve, reject) => {
(<any>window).courseware.getEngineInfo(() => {
resolve((<any>window).air.engineInfo);
});
});
}
}
asyncCallNetworkApiGet(apiName, data) {
return new Promise((resolve, reject) => {
this.callNetworkApiGet(apiName, data, (res => {
resolve(res);
}));
});
}
asyncCallNetworkApiPost(uri, data) {
return new Promise((resolve, reject) => {
this.callNetworkApiPost(uri, data, (res) => {
resolve(res);
});
});
}
} }
\ No newline at end of file
declare const global:any = {};
/** !#en /** !#en
The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace.
!#zh !#zh
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment