无法在$ httpInterceptor中读取未定义的属性'push'

时间:2016-10-19 07:13:24

标签: angularjs http angular-http-interceptors

我想在我的应用中为所有$ http请求发送默认数据参数。 我提到了这个答案$httpInterceptor。我可以设置默认标头,但参数不起作用。我明白我想发送一个数组来推送到Json对象,我试过了。

angular
    .module('app.main')
    .factory('myHttpInterceptor', myHttpInterceptor);

myHttpInterceptor.$inject = ['Constant'];

function myHttpInterceptor(Constant) {
    var data = [{'foo': 'fooBar'}];
    return {
        request: requestInterceptor
    };

    function requestInterceptor(config) {
        config.params.push(data);
        return config;
    }
}

在我的app.module中我指定了这个

app.config([...,'$httpProvider'...){
$httpProvider.interceptors.push('myHttpInterceptor');
}

然后在config.params.push中出现错误

我想发送一个默认参数,如

  

foo:fooBar

我的所有http请求,谢谢

2 个答案:

答案 0 :(得分:0)

我认为你推动时没有params数组。试试这段代码。

初始化angular .module('app.main') .factory('myHttpInterceptor', myHttpInterceptor); myHttpInterceptor.$inject = ['Constant']; function myHttpInterceptor(Constant) { var data = [{'foo': 'fooBar'}]; return { request: requestInterceptor }; function requestInterceptor(config) { if(config.params.length != 0) { config.params.push(data); } else { config.params = [] config.params.push(data); } return config; } } ,如果它不存在。然后按下它。

{{1}}

如果存在,则推送到params,或创建新的params

这可以解决您的问题。

答案 1 :(得分:0)

如果数组未定义,则需要创建数组。

function myHttpInterceptor(Constant) {
    var data = [{'foo': 'fooBar'}];
    return {
        request: requestInterceptor
    };

    function requestInterceptor(config) {
        config.params = config.params || [];
        config.params.push(data);
        return config;
    }
}