我想做的是用ES6创建一个角度模型(例如Book),可以用一些参数实例化(新书(' someTitle'))。我已经使用了以下内容(假设我们需要注入一些内容,例如$ http):
function foo($http) {
return class Book {
constructor(title) {
this.title = title;
}
fetch() {
return $http.get('api/book/' + this.title);
//...
}
};
}
angular.module('app')
.service('Book', ['$http', function($http) {
return foo($http);
}];
问题在于,这似乎不是一种干净的做事方式。此外,我不确定会出现什么问题。任何人都可以建议一个更好的方法来实现同样的目标吗?
答案 0 :(得分:1)
我在Typescript中完成了这个,而不是将类包装在一个函数中,我有一个静态工厂函数,它返回一个类的工厂......这可能看起来更清晰一些。看起来像这样...
class Book {
constructor(public $http) {}
set(title) {
this.title = title;
}
fetch() {
return this.$http.get('api/book/' + this.title);
}
static factory () {
let service = ($http) => {
return new Book($http);
}
service.inject = ['$http'];
return service;
}
}
angular.module('app')
.service('Book', Book.factory());
另一种让它看起来非常干净的方法是他们在Angular2中所做的是ES2016 / 2017装饰器,它们目前在Typescript中工作。无论如何,只是一个想法!
答案 1 :(得分:0)
您可以创建一个具有工厂定义的类,并且创建静态方法将允许您通过类名访问方法。
class refreshFactory {
constructor($scope) {
'ngInject';
this.callbacks = {};
this.$scope = $scope;
}
testmethod () {
alert();
}
static refreshFunctions ($scope) {
'ngInject';
return new refreshFactory($scope);
}
}
export default refreshFactory;
// Create the module where our functionality can attach to
let CommonFactory = angular.module('common.factories', []);
import refreshFactory from './refresh.factory';
CommonFactory.factory('refreshFactory', refreshFactory.refreshFunctions);