Meteor-Angular 1.5 服务不工作

Meteor-Angular 1.5 services not working

我一直在尝试创建一个服务来在 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
});

我似乎无法将服务注入 component.What 我做错了吗?

解决方案:

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

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
})

希望这对您有所帮助:)

我能够通过执行您所做的并添加 "ngInject" 来使用 angular 和 meteor 1.3 设置服务;给构造函数。这就是它的样子

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";
    };
});;