我正在重写ES6中的所有AngularJs代码。我有一个用户服务,它是一个返回$resource
对象的工厂:
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'
}
}
});
});
它已被重写如下:
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);
然而,它打破了我的旧控制器,因为我必须像往常一样使用User.resource
而不是普通的User
。有没有解决方法来实现这个目标?
答案 0 :(得分:2)
尝试:
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"];
然后在你的模块中:
import Factory from "path_to_your_factory_file";
angular.module(name, [ngResource]).factory("Factory", Factory.activate);
享受!