先贴代码
var app = angular.module('myApp', []); app.controller('siteCtrl', function ($scope, $http) { $http.get("http://www.runoob.com/try/angularjs/data/sites.php") .success(function (response) { console.log(response); }) .error(function (response) { console.error(response); }); }); //全局$http请求 app.config(function ($httpProvider) { $httpProvider.interceptors.push(function ($q) { return { 'request': function (config) { var deferred = $q.defer(); deferred.reject({ "data": { "sites": [{ "Name": "菜鸟教程", "Url": "www.runoob.com", "Country": "CN" }, {"Name": "Google", "Url": "www.google.com", "Country": "USA"}, { "Name": "Facebook", "Url": "www.facebook.com", "Country": "USA" }, {"Name": "微博", "Url": "www.weibo.com", "Country": "CN"}] }, "status": 200, "config": { "method": "GET", "transformRequest": [null], "transformResponse": [null], "url": "http://www.runoob.com/try/angularjs/data/sites.php", "headers": {"Accept": "application/json, text/plain, */*"} }, "statusText": "OK" }); return deferred.promise; }, 'response': function (config) { return config; } }; }); });
上面会返回 resolve 下的json 但是不是在$http 的 success 下回调返回的,是在 error 下,这里默认为 错误,能不能在success返回,前提是在不请求的情况下直接返回 成功 的 响应到 $http 服务,这个能在拦截器上做吗?目的就是某些规则的url请求不发送,直接在返回结果。
如果要在拦截器里面阻止请求就要在request
$httpProvider.interceptors.push(function($q) { return { 'request': function(config) { return $q.reject("abc"); // 直接返回拒绝的promise } }; });
但是这样做不符合response的success,认为请求是失败的,所以总体来说不应该在拦截器里面去做拦截真实请求,返回成功模拟数据,你可以把所有请求包一层request.service,在这一层里面去做规则。