我有一个像下面这样的会话服务,有两种方法代表两种验证方式:
angular
.module('myApp')
.service('sessionService', SessionService);
function SessionService() {
var $ctrl = this;
this.logInTypeA = function(username, password, authenticator) {
...
}
this.logInTypeB = function(username, password, authenticator) {
...
}
...
}
我有一个登录表单组件。我希望有两个表单实例使用两种不同的登录方法,但在其他方面是相同的:
<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeA"></log-in-form>
<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeB"></log-in-form>
组件的JS看起来像这样:
angular
.module('myApp')
.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '&'
}
});
function LogInFormController() {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
$ctrl.logInMethod($ctrl.username, $ctrl.password, $ctrl.authenticator);
};
...
}
但是,当我尝试运行时出现错误:
TypeError: Cannot use 'in' operator to search for '$ctrl' in testloginemail@example.com
如何将服务中的方法传递给组件?
提前致谢。
答案 0 :(得分:5)
您的HTML在服务名称中有拼写错误。以下是我在Angular 1.4.x中的操作方法。
在HTML中,您应该添加被调用函数的参数:
<log-in-form log-in-method="$ctrl.sessionService.logInTypeA(username, password, authenticator)"></log-in-form>
<log-in-form log-in-method="$ctrl.sessionService.logInTypeB(username, password, authenticator)"></log-in-form>
对于组件,您需要在参数周围添加花括号并添加每个参数名称:
angular
.module('myApp')
.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '&'
}
});
function LogInFormController() {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
$ctrl.logInMethod({username: $ctrl.username,
password: $ctrl.password,
authenticator: $ctrl.authenticator});
};
...
}
答案 1 :(得分:0)
如果您希望代码按名称使用服务功能:
<log-in-form log-in-method="logInTypeA"></log-in-form>
<log-in-form log-in-method="logInTypeB"></log-in-form>
使用属性@
绑定,并在组件中注入服务:
app.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '@'
}
});
function LogInFormController(sessionService) {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
var method = sessionService[$ctrl.logInMethod];
method($ctrl.username, $ctrl.password, $ctrl.authenticator);
};
...
}
使用property accessor bracket notation按名称选择所需的服务方法。