如何在angular中使构造函数之外的服务可用

How do I make services available outside of constructor in angular?

本文关键字:服务 构造函数 angular      更新时间:2023-09-26

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

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函数添加到作用域是否正确,或者是否有更简单的方法使其可用于模板?

Thx提前

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

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