【问题标题】:How do I make services available outside of constructor in angular?如何以角度在构造函数之外提供服务?
【发布时间】:2016-09-05 09:17:00
【问题描述】:

我有以下问题。当我有一个带有角度的离子类时,我可以在注入它们后在构造函数中访问角度服务:

export class HomeController {
    static $inject = [
        '$scope',
        '$state'
    ];

    constructor(
       public $scope : any,
       public $state : any
    ) {
        this.$state.go('test');
        this.$scope.changeController = this.changeController;
    }

    changeController() {
        console.log("change controller");
    };
}

但是当我将其更改为更改控制器功能时,它不起作用

export class HomeController {
    static $inject = [
        '$scope',
        '$state'
    ];

    constructor(
       public $scope : any,
       public $state : any
    ) {
        this.$scope.changeController = this.changeController;
    }

    changeController() {
        console.log("change controller");
        this.$state.go('test'); // Fails here
    };
}

这是错误:

错误:未定义不是一个对象(评估 'this.$state.go')

我能做什么?

最重要的是,将 changeController 函数添加到范围是否正确,或者是否有更简单的方法使其可用于模板?

提前谢谢

【问题讨论】:

  • 也许this 是未定义的。你试过changeController() => {...}吗?

标签: javascript angularjs typescript ionic-framework


【解决方案1】:

在您的情况下,this 的值不正确,这是由于对 ES6 类的误解而非常常见的问题。尝试使用 lambda 进行词法作用域:

  changeController = () => {
    console.log("change controller");
    this.$state.go('test'); // Fails here
  };

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2021-07-09
    • 2022-07-22
    • 2016-07-16
    • 1970-01-01
    • 2019-01-16
    相关资源
    最近更新 更多