【问题标题】:TypeError defining/accessing interceptors in AngularJS/TypeScript/ES6TypeError 在 AngularJS/TypeScript/ES6 中定义/访问拦截器
【发布时间】:2016-04-25 11:43:55
【问题描述】:

我有以下拦截器:

"use strict";

import { IApiService } from '../services/api';
import { ISessionService } from '../services/session';
import { IRedirectService } from '../services/redirect';

export default class ApiInterceptor {

  constructor(
    private $q: ng.IQService,
    private ApiService: IApiService,
    private SessionService: ISessionService,
    private RedirectService: IRedirectService) { }

  ...

}

这是它作为服务的设置方式:

import ApiInterceptor          from './interceptors/api';
...

export default angular.module('app.core', [
    'toastr', 'js-data'
  ])

  // Constants
  .constant('config', config)

  // Config
  .config(DataConfig)

  // Filters
  ...

  // Interceptors
  .service('ApiInterceptor', ApiInterceptor);

然后在我的app.instance 中,我将app.core 设置为 dep:

'use strict';

import '../app.core/module';
...

export default angular.module('app.instance', [
  ...
  'app.core',
  ...]);

并在这里使用它的代码:

'use strict';

import '../../app.core/module';
...

export default function ConfigApp($httpProvider, $locationProvider, $analyticsProvider): void {
  ...
  $httpProvider.interceptors.push('ApiInterceptor');
  ...
}

然后我得到这个错误:

Uncaught TypeError: Cannot read property 'prototype' of undefined

这是我从调试器获得的信息:

向上调用堆栈:

有什么想法吗?从昨天开始,我一直在用头撞墙…… 谢谢!

编辑:

这是一个服务示例:

.service('LogService', LogService)

这是实现:

"use strict";

export interface ILogService {
  debug(...args: any[]): void;
  info(...args: any[]): void;
  warn(...args: any[]): void;
  error(...args: any[]): void;
  deprecated(...args: any[]): void;
  enableDebug(flag: boolean): void;
  enableConsole(flag: boolean): void;
}

/**
 * Provides logging support.
 */
export default class LogService implements ILogService {

  static debugEnabled: boolean = false;
  static consoleEnabled: boolean = true;

  constructor(
    private $log: any,
    private $window: ng.IWindowService) { }

我得到同样的错误......

【问题讨论】:

    标签: javascript angularjs typescript ecmascript-6


    【解决方案1】:

    来自您的代码:

    // Interceptors
      .service('ApiInterceptor', ApiInterceptor);
    

    Angular 拦截器是 factories,你不能为它使用 classes。 :

    // Interceptors
      .factory('ApiInterceptor', somePlainOldFunctionAndNotAClassConstructor);
    

    【讨论】:

    • 好的,在发帖之前我确实试过了。我的代码是这样的:.factory('ApiInterceptor', function() { return { get: function() { return ApiInterceptor;} }; }) 但效果不佳,因为对象始终未定义。还是我做错了?谢谢你的回答,顺便说一句。
    • 另外,我忘了提一下,我的服务也会发生同样的事情:.service('SessionService', SessionService) 其中SessionService 也是一个类。
    • Or did I do it incorrectly. 是的。你想返回一个实例。只是把它包装起来返回类并不能解决任何问题
    • Also, I forgot to mention, the same thing happen with my services: 这是一个单独的问题。
    • 谢谢!但是解决方案是一样的吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多