【问题标题】:Angular $interval is not a function issue角度 $interval 不是函数问题
【发布时间】:2017-02-27 14:19:38
【问题描述】:

我知道您可能会将其标记为重复,但没有一个兄弟主题不能解决我的问题,所以这是我的简单日期倒计时指令:

class Clock {
    constructor() {
        this.restrict = 'AC';
        this.replace = true;
        this.template = require('./templates/clock.tpl.html');
        this.scope = {};
    }
    link(scope, elem, attrs, $interval) {
        let end = new Date('05/05/2017 9:00 AM');

        let _second = 1000;
        let _minute = _second * 60;
        let _hour = _minute * 60;
        let _day = _hour * 24;

        scope.showRemaining = () => {
            let now = new Date();
            let distance = end - now;
            let days = Math.floor(distance / _day);
            let hours = Math.floor((distance % _day) / _hour);
            let minutes = Math.floor((distance % _hour) / _minute);
            let seconds = Math.floor((distance % _minute) / _second);

            scope.days = days;
            scope.hours = hours;
            scope.minutes = minutes;
            scope.seconds = seconds;
        }

        $interval(showRemaining, 1000;)
    }
}

// create factory function to handle DI
function factory() {
    "ngInject";

    return new Clock();
}

export default factory;

我一直在搜索这个问题的原因,并且在任何地方我都得到信息,即间隔函数必须作为普通函数传递,不带参数或任何其他插件。但我仍然有同样的错误,即:

TypeError: $interval is not a function

有人可以帮忙吗?

【问题讨论】:

  • 通过控制器注入,而不是链接函数

标签: javascript angularjs directive clock


【解决方案1】:

您必须在构造函数中注入依赖项,而不是在 link 函数中:

constructor($interval) {
    // ..
    this.$interval = $interval;
}
link(scope, elem, attrs) {
    // ..
    this.$interval(showRemaining, 1000;)
}

【讨论】:

  • 赞成,虽然我不认为他在打字
  • 是的,这不是打字稿
  • 你当然也得把它传给你工厂函数中的构造函数
  • 这行不通。指令中的 link 函数(上面的类是 DDO 对象的构造函数)没有 this
【解决方案2】:

使用类构造指令对象的问题是指令函数具有非词法this(有关详细信息,请参阅this answer)。可以将$interval 注入到构造函数中,但是如果不绑定它就无法从link 函数中使用它:

constructor($interval) {
  ...
  this.$interval = $interval;
  this.link = this.link.bind(this);
}

这表明存在设计问题。指令不适合类。使用它们来构造指令对象没有好处。这些类不可重用。它们没有架构优势。

Angular 1.5+ 借鉴了 Angular 2 的想法(使迁移更容易是当前版本的任务之一)并使开发以控制器为中心。这导致用$onInit$postLink 挂钩替换了预链接和后链接功能。

基于类的 AngularJS 开发的实用方法可能如下所示:

class ClockController {
  constructor($interval) {
    this.$interval = $interval;
  }

  $onInit() {
    this.$interval(() => this.showRemaining(), 1000);
  }

  showRemaining() { ... }
}

app.directive('clock', () => ({
  ...
  controller: ClockController
}));

此时将此指令转换为组件是有意义的,因为这是组件所做的。它们基本上是强制以控制器为中心的方法的指令的包装器。

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2020-05-09
    • 2021-05-02
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2018-04-19
    相关资源
    最近更新 更多