1

I want to create a service that can be injected into different controllers for using an entity called Contact.

I have a .js file where everything is configured and I import the service there like this:

import ContactService from './service/ContactService';
import ContactsController from './ContactsController';
//...
angular.module(name,[
   //...
   ]).service('contactService', ContactService)
     .controller('contactsController', ContactsController)
//...

In ContactsController.js I want to use the service like this:

export default ($scope, contactService) => {
   $scope.contacts = contactService.get();
}

Then in my ContactService.js I tried to do this, but it's not working

var Contact;
class ContactService {

    constructor($resource) {
        Contact = $resource('/contacts/:id');
    }

    get(id) {
        return Contact.get(id);
    }

    get() {
        return Contact.query();
    }

    //...
}
ContactService.$inject = ['$resource'];
export default ContactService;

How can I nicely implement ContactService.js so that it's working using the ES6 class and $resource?

2
  • try using writing it as this.Contact = $resource(...); and accessing it with return this.Contact; Commented Jul 23, 2018 at 13:58
  • @AlekseySolovey not working...but maybe I wrote your snippets at the wrong places, idk Commented Jul 23, 2018 at 14:02

1 Answer 1

1

The constructor needs to use the this object:

̶v̶a̶r̶ ̶C̶o̶n̶t̶a̶c̶t̶;̶
class ContactService {

    constructor($resource) {
        ̶C̶o̶n̶t̶a̶c̶t̶ ̶=̶ ̶$̶r̶e̶s̶o̶u̶r̶c̶e̶(̶'̶/̶c̶o̶n̶t̶a̶c̶t̶s̶/̶:̶i̶d̶'̶)̶;̶ 
        this.Contact = $resource('/contacts/:id');
    }

    get(id) {
        return this.Contact.get(id);
    }

    getAll() {
        return this.Contact.query();
    }

    //...
}
ContactService.$inject = ['$resource'];
export default ContactService;

Also since the code uses classes, avoid using $scope in the controller:

class ContactsController {
    constructor (contactService) {}
        this.contactService = contactService;
    }
    $ngInit () {
        this.contacts = this.contactService.get();
    }
}

ContactsController.$inject = ['contactService'];
export default ContactsController; 
Sign up to request clarification or add additional context in comments.

1 Comment

I found my problem: The first / in '/contacts/:id' - without it everything works! But either way your solution isn't wrong and a good starting point for me to refactor my architecture into classes, so I give you the checkbox :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.