Cold_Class
Cold_Class

Reputation: 3484

Create service using ES6 class and $resource

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?

Upvotes: 1

Views: 2178

Answers (1)

georgeawg
georgeawg

Reputation: 48968

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; 

Upvotes: 1

Related Questions