【发布时间】:2016-03-31 05:47:15
【问题描述】:
我正在玩 angularjs services 和 factories。我创建了一个名为BookFactory 的工厂,如下所示:
// Code goes here
app
.factory('BootFactory', function() {
var bookFactory;
function add() {
}
function remove() {
}
function getAll() {
}
bookFactory = {
add: add,
remove: remove,
getAll: getAll
}
return bookFactory;
});
还有一个BookService如下:
app.service('BookService', function() {
var bookService;
function add() {
}
function remove() {
}
function getAll() {
}
/*
It throws:
Uncaught ReferenceError: Invalid left-hand side in assignment.
How can I achieve the same structure with the services which I have used in factories.
this = {
add: add,
remove: remove,
getAll: getAll
};
*/
//Do I have to add all methods like this
this.add=add;
this.remove=remove;
this.getAll=getgAll;
//Or there's any other better way to achieve it
});
我想要做的是保持结构一致,即我想要工厂和服务都像这样:
bookFactory = {
add: add,
remove: remove,
getAll: getAll
}
在工厂的情况下,它工作正常。但在服务的情况下,我不能这样做。因为服务与this 一起工作,我不能这样做:
/*
It throws:
Uncaught ReferenceError: Invalid left-hand side in assignment.
How can I achieve the same structure with the services which I have used in factories.
this = {
add: add,
remove: remove,
getAll: getAll
};
*/
我想做的是:
//Do I have to add all methods like this
this.add=add;
this.remove=remove;
this.getAll=getgAll;
//Or there's any other better way to achieve it
有没有更好的方法呢?这是plunkr。
【问题讨论】:
标签: javascript angularjs factory plunker