Meteor-Angular 1.5服务不起作用

时间:2016-04-16 00:07:25

标签: angularjs meteor angular-meteor

我一直在尝试创建一个服务来在Meteor 1.3中的两个不同组件之间共享代码,但到目前为止已经非常不成功。创建和注入Angular 1服务似乎不起作用。

我有像这样的Angular服务:

angular.module(name).service("myService", function () {
    this.somevariable = 'somevalue';
});

我有一个像这样的登录组件:

class Login {
    constructor($scope, $reactive, $state, myService) {
        console.log(myService.somevariable) //doesn't work
    }
}

// create a module
export default angular.module(name, [
    angularMeteor
]).component(name, {
    templateUrl: 'imports/ui/components/${name}/${name}.html',
    controllerAs: name,
    controller: Login
});

我似乎无法在组件中注入服务。我做错了什么?

SOLUTION:

我需要一项服务来使用正则表达式验证电子邮件地址。我是这样做的:

import angular from 'angular';
import angularMeteor from 'angular-meteor';
class Validator { 
    validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }
}

const name = 'validator';

// create a module
export default angular.module(name, [
    angularMeteor
])

.service("Validator", Validator);
然后我按照这样注入服务:

import {name as Validator} from '../../../api/services/validator'

class Login {
    constructor($scope, $reactive, $state, Validator) {
        'ngInject';
        this.$state = $state;

        $reactive(this).attach($scope);
        this.Validator = Validator;
    }

    login() {
        if(this.Validator.validateEmail(this.credentials.email)) {
            // email is valid. 
        }
    }    
}

const name = 'login';

export default angular.module(name, [
    angularMeteor,
    Validator
]).component(name, {
    templateUrl: `imports/ui/components/${name}/${name}.html`,
    controllerAs: name,
    controller:Login
})

希望这会有所帮助:)

1 个答案:

答案 0 :(得分:0)

我能够通过你所做的事情设置角度和流星1.3的服务,但也添加&#34; ngInject&#34 ;;到构造函数。这就是它的样子

class Login {
    constructor($scope, $reactive, $state, myService) {
        "ngInject"; //this is needed to inject
        console.log(userService.getStuff());
    }
}

// create a module
export default angular.module(name, [
    angularMeteor
]).component(name, {
    templateUrl: 'imports/ui/components/${name}/${name}.html',
    controllerAs: name,
    controller: Login
}).service("userService", function () {
    this.getStuff = function() {
        return "Got Stuff";
    };
});;