javascript - angular 拦截器不请求,实现直接返回成功结果。

 待续爱情2502861755 发布于 2022-11-11 13:47

先贴代码

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请求不发送,直接在返回结果。

1 个回答
  • 如果要在拦截器里面阻止请求就要在request

    $httpProvider.interceptors.push(function($q) { 
        return {
            'request': function(config) {
                return $q.reject("abc"); // 直接返回拒绝的promise
            }
        };
    });

    但是这样做不符合response的success,认为请求是失败的,所以总体来说不应该在拦截器里面去做拦截真实请求,返回成功模拟数据,你可以把所有请求包一层request.service,在这一层里面去做规则。

    2022-11-12 01:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有