實(shí)際上我們會經(jīng)常使用HTTP請求時(shí)候做一個(gè)加載提示牵寺,但是每次都去寫ionicLoading確實(shí)很麻煩即寒,我們可以在使用interceptor攔截器做統(tǒng)一的處理瞧挤。
比如官網(wǎng)介紹的方法:
http://learn.ionicframework.online/formulas/loading-screen-with-interceptors/
var app = angular.module('ionicApp', ['ionic'])
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
$rootScope.$broadcast('loading:show')
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
})
})
app.run(function($rootScope, $ionicLoading) {
$rootScope.$on('loading:show', function() {
$ionicLoading.show({template: 'foo'})
})
$rootScope.$on('loading:hide', function() {
$ionicLoading.hide()
})
})
app.controller('MainCtrl', function($http, $ionicLoading) {
var _this = this
$http.jsonp('http://api.openbeerdatabase.com/v1/breweries.json?callback=JSON_CALLBACK').then(function(result) {
_this.breweries = result.data.breweries
})
})
通過代碼闷沥,可以看出來是借助于$rootScope的$broadcast和$on來傳播和接收事件,從而控制提示框的顯示和隱藏瘫证。
事實(shí)上揉阎,我們也可以通過$injector本身來獲取到具體的服務(wù),比如下面的代碼:
request: function (config) {
if (config.url.toString().indexOf('http://') === 0) {
$injector.get('$ionicLoading').show({
template: '<div><svg class="circular"><circle r="20" class="path" cx="50" cy="50" fill="none" stroke-width="2" stroke-miterlimit="10"></circle></svg>'
});
}
config.headers = config.headers || {};
return config;
}
是不是簡單多了背捌,實(shí)際使用項(xiàng)目的時(shí)候毙籽,我偏向于后一種方法,而盡量減少使用$rootScope避免全局變量污染毡庆。