Services in Meteor 1.3 with Angular 1.5

I’ve been trying to create a service to share code between two different components in Meteor 1.3, but have been spectacularly unsuccessful so far. Creating and injecting Angular 1 services just doesn’t seem to work.

I have an Angular service like so:

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

I have a login component like so:

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

I just cant seem to be able to get the service injected in the component.What am I doing wrong?

I can’t seem to find anywhere whre you refered to [quote=“hgadgil, post:1, topic:21494”]
userService
[/quote]

in your sample code.

Sorry. Code has been updated.

try adding

'ngInject'

after that line and make sure you have the pbastowski:angular-babel installed and ecmascript removed.

running into this issue as well. were you able to get it to work?

Yes.

I needed a service to validate an email address using a regular expression. I did it like this:

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

I then injected the service like so:

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

Hope this helps :slight_smile:

2 Likes

Thanks! I was missing the ‘ngInject’ and had forgotten to import the module that contained the service, and register it as a dependency in the current module.

Minor tweak, avoid ../../../../ in the imports just use import '/imports/...' saves brain cells.

1 Like

thanks! this post has helped quite a bit.

Thanks for sharing! This was very helpful for me

1 Like