Reputation: 15259
I'm rewriting all my AngularJs code in ES6. I have a User service that is a factory which returns the $resource
object:
angular.module('cdcApp')
.factory('User', function ($resource) {
return $resource('/api/users/:id/:controller', {
id: '@_id'
},
{
changePassword: {
method: 'PUT',
params: {
controller:'password'
}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
});
It has been rewritten as the following:
class User {
constructor($resource) {
this.$resource = $resource;
this.resource = this.$resource('/api/users/:id/:controller', {
id: '@_id'
}, {
changePassword: {
method: 'PUT',
params: {
controller: 'password'
}
},
get: {
method: 'GET',
params: {
id: 'me'
}
}
});
}
}
angular.module('cdcApp')
.service('User', User);
However, it broke my old controller as I must use User.resource
instead of just normal User
as usual. Is there any workaround to achieve this?
Upvotes: 0
Views: 703
Reputation: 59
try:
export default class Factory {
constructor (API_ENDPOINT, $resource) {
return $resource(API_ENDPOINT + "/url", {id: "@id"}, {
update: {
method: "PUT"
}
});
}
static activate(API_ENDPOINT, $resource) {
Factory.instance = new Factory(API_ENDPOINT, $resource);
return Factory.instance;
}
}
Factory.$inject = ["API_ENDPOINT", "$resource"];
then in your module:
import Factory from "path_to_your_factory_file";
angular.module(name, [ngResource]).factory("Factory", Factory.activate);
Enjoy!
Upvotes: 2