使用toastr注入服务的angularjs httpInterceptor的无限循环

时间:2018-03-19 11:45:26

标签: javascript angularjs ecmascript-6 angular-http-interceptors toastr

我正在使用我的httpInterceptor和我的toastr服务。它总是会产生无限循环

  • AlertService(使用toastr)
class AlertService {

    constructor(toastr) {
        this.toastr = toastr;
        this.toastrCommonOpts = {
            positionClass: "toast-bottom-center",
            allowHtml: true,
            closeButton: true,
        }
    }

    notificationError (msg, title) {
        let errorMsg = msg || 'error';
        this.toastr.error(errorMsg, title || '', this.toastrCommonOpts);
    };

    notificationWarning(msg, title) {
        let warningMsg = msg || 'warning';
        this.toastr.warning(warningMsg, title || '', this.toastrCommonOpts);
    }

    notificationSuccess(msg, title, duration) {
        let successMsg = msg || 'Success';
        this.toastr.success(successMsg, title || '', this.toastrCommonOpts);
    }

}
AlertService.$inject = ['toastr'];
export default AlertService ;
  • myHttpInterceptor
class HttpInterceptor {
    constructor() {
        ['request', 'response']
            .forEach((method) => {
                if(this[method]) {
                    this[method] = this[method].bind(this);
                }
            });
    }
}
class MyHttpInterceptor extends HttpInterceptor{

    constructor(AlertService) {
        super();
        this.AlertService = AlertService;
    }

    request(config) {
        this.AlertService.notificationSuccess();
        return config;
    };


    response(response){
        this.AlertService.notificationSuccess();
        return response;
    }
}

MyHttpInterceptor.$inject = ['AlertService'];
export default MyHttpInterceptor;
  • Mymodule中
import MyHttpInterceptor from './myHttpInterceptor';
import AlertService from "./alert.service";

export default angular.module('app.core', [toastr])
    .service('AlertService', AlertService)
    .factory('MyHttpInterceptor', MyHttpInterceptor)
    .config(($httpProvider) => {
        $httpProvider.defaults.withCredentials = true;
        $httpProvider.interceptors.push('MyHttpInterceptor');
    });

我扩展myHttpInterceptor并绑定我的方法以防止丢失上下文'this'(cf:angularjs http interceptor class (ES6) loses binding to 'this')。我没有成功使用arrowFunctions作为类方法。

我也尝试按照this issue

进行操作

你们中间有人遇到过这个问题吗?

谢谢:)

0 个答案:

没有答案