gpt4 book ai didi

javascript - Angularjs:实现与工厂相同的服务结构

转载 作者:行者123 更新时间:2023-11-28 15:11:22 25 4
gpt4 key购买 nike

我正在使用angularjs服务工厂。我创建了一个名为 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

最佳答案

您可以像这样创建 bookService -

app.service('BookService', function() {
return {
add:add,
remove:remove,
getAll:getAll
};

function add() {

}

function remove() {

}

function getAll() {

}

});

关于javascript - Angularjs:实现与工厂相同的服务结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com