Services in Meteor 1.3 with Angular 1.5


#1

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?


Export / Import - confused!
#2

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

in your sample code.


#3

Sorry. Code has been updated.


#4

try adding

'ngInject'

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


#5

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


#6

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:


#7

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.


#8

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


#9

thanks! this post has helped quite a bit.


#10

Thanks for sharing! This was very helpful for me