如何在angular中使构造函数之外的服务可用
How do I make services available outside of constructor in angular?
我有以下问题。当我在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
};
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 拦截对构造函数的调用
- 使用闭包共享构造函数参数
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 从js引擎的角度来看闭包和构造函数是如何工作的
- 如何使用此从对象访问构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 当一个重要的构造函数参数丢失时应该发生什么
- Chrome Javascript日期构造函数错误
- 如何在angular中使构造函数之外的服务可用
- $q服务 - 我应该在新的 AngularJS 应用程序中使用 CommonJS 风格还是构造函数风格
- 尝试将 AngularJS 服务用作构造函数时出错
- 服务构造函数参数
- 当将服务注入(导入)到我的构造函数中时;无提供者”;错误
- JavaScript服务:如何提供()方法,比如对象构造函数