Angular服務(wù)Request異步請(qǐng)求的實(shí)例講解
首先這里我簡單寫個(gè)例子來方便您的理解
var request = {
post: function() {
var errorCallback = {
error: function(f) {
this.fun = f;
},
fun: function(data) {}
};
successCallback = {
success: function(f) {
return this.fun = f, console.log(this.fun), errorCallback;
},
fun: function(data) {
console.log(data)
}
};
returnData = {
wsscat: "hello"
};
//成功
//var a = successCallback.fun(returnData);
a = successCallback.fun;
setTimeout('a(returnData)', 1000)
return successCallback;
}
}
request.post().success(function(data) {
console.log("123");
console.log(data);
})
console.log("wscat's test");
這里首先要理解一點(diǎn)很重要的就是異步回調(diào),Javascript的異步回調(diào)其實(shí)就兩個(gè)常用方法,
setTimeout定時(shí)這類和ajax請(qǐng)求這類
上面代碼跟angular的request服務(wù)類似,首先是這個(gè)request對(duì)象,就相當(dāng)于angular注入request服務(wù)之后返回的request對(duì)象
這個(gè)對(duì)象寫了一個(gè)post方法,而post方法里面這有兩個(gè)回調(diào)對(duì)象分別是
errorCallback和successCallback
還有一個(gè)模擬ajax請(qǐng)求返回的returnData對(duì)象
returnData = {
wsscat: "hello"
};
這個(gè)在angular里面則是ajax請(qǐng)求服務(wù)器返回給你的json對(duì)象
我們看看這段代碼執(zhí)行之后會(huì)log出什么的信息,如下圖

如果熟悉Javascript的話這里不難理解,首先是輸出的函數(shù)信息是因?yàn)閟uccess()函數(shù)里面的console.log(this.fun)這句
request.post().success()
success()里面首先this.fun = f這句是,把匿名的回調(diào)函數(shù)賦給successCallback對(duì)象里面的fun方法,保存起來讓后面setTimeout進(jìn)行回調(diào)
所以我們可以看到首先執(zhí)行出來的是打印出來的回調(diào)函數(shù),然后就是代碼最后一句的
console.log("wscat's test");
明白了上述這個(gè)流程之后就可以很好的理解angular封裝的request服務(wù)這一塊
只不過angular里面的回調(diào)不是setTimeout回調(diào),而是換成了$http回調(diào)而已
$http.get(url).success(function(data, status, headers, config) {
//code
})
而$http請(qǐng)求又因?yàn)楦鶕?jù)返回的成功或者失敗把數(shù)據(jù)
用相應(yīng)的方法帶到我們放到了被匿名回調(diào)函數(shù)覆蓋,對(duì)象successCallback的fun里面
而帶數(shù)據(jù)到fun里面就是下面這兩句
successCallback.fun(returnData); errorCallback.fun(returnData);
后面我再深入說一下
$http.get(url).success(function(data, status, headers, config) {
//code
})
data:這個(gè)不用再多敘述了,我們上面做了這么多其實(shí)就是想拿服務(wù)器返回給我們的data
status:http響應(yīng)狀態(tài)碼,這個(gè)是很基礎(chǔ)的東西,但我還是簡單說說
200:不用懷疑就是請(qǐng)求成功的意思
304:就是你請(qǐng)求已經(jīng)被允許的情況下,服務(wù)器發(fā)現(xiàn)你需要的東西還是跟之前一樣沒變,則返回給你304
404:請(qǐng)求失敗了,請(qǐng)求的資源再服務(wù)器沒有發(fā)現(xiàn)
500:看到5一般就是服務(wù)器出錯(cuò)了
常看到的就這幾個(gè)吧
header:頭信息
config:生成原始請(qǐng)求的設(shè)置對(duì)象,如下圖

再往下看,其實(shí)post請(qǐng)求和get請(qǐng)求區(qū)別是不大的
只是這里get更簡單明了,你直接傳url過來就行了,相比post請(qǐng)求接口還要帶上各種需要請(qǐng)求的參數(shù)
但再仔細(xì)了解的話,其實(shí)post跟get在這里其實(shí)都走get請(qǐng)求

Request服務(wù)源碼
.service('Request', [
'$http',
'$cookies',
'$rootScope',
'$window',
'$cookieStore',
'$location',
function($http, $cookies, $rootScope, $window, $cookieStore, $location) {
var request = {
post: function(api, map, successCallback) {
$rootScope.dataLoadCount++;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
var url = '../test.php?api=' + encodeURIComponent(api);
//console.log('[http requestURL]:' + api);
//~ alert(api);
var json = '{}';
if (angular.isDefined(map)) {
json = angular.toJson(map);
}
//console.log('[http requestJson]:' + json);
url += '&data=' + encodeURIComponent(json);
var errorCallback = {
error: function(f) {
this.fun = f;
},
fun: function(data) {}
};
var successCallback = {
success: function(f) {
return this.fun = f, errorCallback;
},
fun: function(data) {}
};
$http.get(url).success(function(data, status, headers, config) {
console.log(config);
// this callback will be called asynchronously
// when the response is available
$rootScope.dataLoadCount--;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
//console.log('[http success responseData]:' + angular.toJson(data));
//~ alert('[http success responseData]:'+angular.toJson(data));
var returnData = {
code: data.state.code,
msg: data.state.msg,
data: data.data
};
if (returnData.code == 1) {
successCallback.fun(returnData);
} else {
if (returnData.code == 99) {
alert(returnData.msg);
$cookieStore.remove('token');
$cookieStore.remove('userid');
delete $cookies.token;
delete $cookies.userid;
$rootScope.isLogined = false;
$rootScope.$broadcast('refreshFooter');
switch ($rootScope.isWeiXinLogin()) {
case true:
$location.path('login');
break;
case false:
$location.path('loginWebapp');
break;
}
return;
}
errorCallback.fun(returnData);
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$rootScope.dataLoadCount--;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
//console.log('[http error responseData]:' + angular.toJson(data));
//~ alert('[http error responseData]:status:'+status);
var returnData = {
code: 0,
msg: '網(wǎng)絡(luò)請(qǐng)求失敗',
data: {}
};
errorCallback.fun(returnData);
});
return successCallback;
},
get: function(url, successCallback) {
$rootScope.dataLoadCount++;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
var errorCallback = {
error: function(f) {
this.fun = f;
},
fun: function(data) {}
};
var successCallback = {
success: function(f) {
return this.fun = f, errorCallback;
},
fun: function(data) {}
};
$http({
method: 'GET',
url: url
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$rootScope.dataLoadCount--;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
//console.log('[http success responseData]:' + data);
var returnData = {
code: 1,
msg: '請(qǐng)求成功',
data: data
};
successCallback.fun(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$rootScope.dataLoadCount--;
$rootScope.isLoading = $rootScope.dataLoadCount != 0;
//console.log('[http error responseData]:' + angular.toJson(data));
var returnData = {
code: 0,
msg: '網(wǎng)絡(luò)請(qǐng)求失敗',
data: ""
};
errorCallback.fun(returnData);
});
return successCallback;
}
}
return request;
}
])
以上這篇Angular服務(wù)Request異步請(qǐng)求的實(shí)例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Angular 多級(jí)路由實(shí)現(xiàn)登錄頁面跳轉(zhuǎn)(小白教程)
這篇文章主要介紹了Angular 多級(jí)路由實(shí)現(xiàn)登錄頁面跳轉(zhuǎn)(小白教程),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Angularjs 滾動(dòng)加載更多數(shù)據(jù)
AngularJS 通過新的屬性和表達(dá)式擴(kuò)展了 HTML。本文主要給大家介紹Angularjs 滾動(dòng)加載更多數(shù)據(jù)的相關(guān)知識(shí),需要的朋友參考下吧2016-03-03
基于AngularJS+HTML+Groovy實(shí)現(xiàn)登錄功能
AngularJS是一款客戶端MVC的javascript框架,而客戶端MVC代表未來架構(gòu)(為什么要使用MVC+REST+CQRS架構(gòu)),如果你有Struts或SpringMVC等后端MVC框架編程經(jīng)驗(yàn),學(xué)習(xí)Angular會(huì)很快,基本是按照同一個(gè)MVC思路實(shí)現(xiàn)的,本文給大家介紹AngularJS+HTML+Groovy實(shí)現(xiàn)登錄功能2016-02-02
AngularJS基礎(chǔ) ng-srcset 指令簡單示例
本文主要介紹AngularJS ng-srcset 指令,這里對(duì)ng-srcset 指令做了詳細(xì)的資料整理,附有代碼示例,有需要的小伙伴可以參考下2016-08-08

