angularjs同一服务的多个实例 [英] angularjs multiple instances of the same service
问题描述
说我想要一个以上的用户服务实例(selectedUser和currentUser),它们提供相同的功能.目前,我只是通过创建两个从本地函数中提取其定义的服务来解决该问题:
Say I want more than one instance of a user service (selectedUser & currentUser), they provide the same functionality. Currently I just get around the problem by creating two services that pull their definition from a local function:
angular.module('myUserModule', [])
.factory('userFactory', ['$http', '$q', function ($http, $q) {
return function getUser(userId) {
return new $q(function (resolve) {
//Gets the user with the provided userId
}
}
}])
.value('currentUserId', '')
.value('selectedUserId', '')
.service('currentUserService', ['userFactory', 'currentUserId', User])
.service('selectedUserService', ['userFactory', 'selectedUserId', User]);
function User(userFactory, userId) {
var self = this;
var promise = userFactory(userId);
promise.then(function setUserSuccess(result) {
self.user = result;
}
}
只是想知道其他人如何解决这个问题.
Just wondering how other people have approached this problem.
已更新: 只是为了澄清一下,我也将这些服务作为单例使用.
Updated: Just to clarify that I am making use of these services as singletons too.
推荐答案
在一个不相关的问题中,该解决方案最终使用了创建多个实例的工厂:
In an unrelated question the solution ended up using a factory that creates multiple instances:
使用出厂模式.
本质上,如果您具有用户服务,则可以使用工厂返回服务的唯一实例.
In essence, if you have a User service, you can use a factory to return a unique instance of the service.
function User(userId, $http) {
var self = this;
$http.get('/api/user/', {userId: userId}).success(function(result) {
self.details = result.data;
}):
}
userFactory.$inject = ['$http'];
function userFactory($http) {
return function(user) {
return new User(user, $http);
}
}
angular.module('app').factory('user', userFactory);
但是对于此示例,您可以仅使用$resource
.这是一个内置的角度工厂,可返回唯一的Resource实例.
But for this example, you can just use $resource
. This is a built in angular factory that returns unique Resource instances.
这篇关于angularjs同一服务的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!