如何正确使用angular工厂
How to use an angular factory correctly?
我读了很多关于angular依赖注入和工厂与服务的文章,比如这篇——angular。服务vs angular。工厂
我正在努力把它付诸实践,不知道你能否给我一些建议,你会怎么做。
我当前的代码是这样的
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
function mainController($scope, $firebase) {
var db = new Firebase("https://**.firebaseio.com/");
$scope.messages = $firebase(db);
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
$scope.messages.$add({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
};
}
我决定使用角路由,并将这个基本功能拆分为两个不同的控制器,我将在我的测试应用程序中使用。MainController将显示firebase数据库中的所有内容,AdminController将能够向它添加消息
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', $firebase)
//code in here to connect to firebase and add messages
.controller('MainController', function(fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
//code here to retrieve everything from firebase db
})
.controller('AdminController', function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
//code here to add a row to the db
})
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});
我的问题是我不想在每个控制器连接到firebase数据库。我想有一个工厂,为我处理这个,并有可能在其中的功能,我可以从我的控制器调用来查看db中的一切,并添加一些东西到db
工厂()
正如我们所看到的,factory()方法是一种快速创建和配置服务的方法。factory()函数接受两个参数:•name (string)
该参数接受我们想要注册的服务的名称。
•getFn (function)
这个函数在Angular创建服务时运行。
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
});
getFn将在应用程序生命周期期间被调用一次,因为该服务是单例的对象。和其他Angular服务一样,当我们定义服务时,getFn可以接受一个数组或一个
getFn函数可以返回从原始值到函数到对象的任何值(类似于value()函数
angular.module('myApp')
.factory('githubService', [
'$http', function($http) {
return {
getUserEvents: function(username) {
// ...
}
}
}]);
服务()
如果我们想用构造函数注册一个服务的实例,我们可以使用service(),它使我们能够为我们的服务对象注册一个构造函数。service()方法接受两个参数:
•name (string)
该参数接受我们想要注册的服务实例的名称。
•constructor (function)
这是我们将调用来实例化实例的构造函数。对象时,service()函数将使用new关键字实例化实例实例。
var Person = function($http) {
this.getName = function() {
return $http({
method: 'GET',
url: '/api/user'
});
};
};
angular.service('personService', Person);
提供者这些工厂都是通过$提供服务创建的,该服务负责实例化
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
})
// This is equivalent to the
// above use of factory
.provider('myService', {
$get: function() {
return {
'username': 'auser'
}
}
});
当我们可以使用。factory()方法时,为什么还要使用。provider()方法呢?方法?
答案在于我们是否需要能够从外部配置方法返回的服务.provider()方法,使用Angular的.config()函数。不像其他的服务方式
从ng-book您所要做的就是将firebase连接移动到服务中,并在需要的地方注入该服务。这个连接线将在你的应用程序第一次运行时执行,如果你在应用程序运行时预先加载了服务,就像你现在所做的那样:
.factory('fireBaseConnectionService', function($firebase){
var db = $firebase(new Firebase("https://**.firebaseio.com/"));//creating
//the firebase connection this line executes only once when the service is loaded
return{
getMessage:function(){
return db.whatever;
}
}
})
如果你动态加载服务脚本,在你需要它的路由上,它只会在到达该路由时连接到数据库。上面的代码将创建一个到数据库的连接,因为连接行只执行一次。
对于那些对上面的答案和这个链接感兴趣的人- Firebase _ AngularJS这就是我最终做的
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', ["$firebase", function($firebase) {
var db = new Firebase("https://***.firebaseio.com/");
return {
getMessages: function() {
return $firebase(db);
},
addMessage: function(message) {
var messages = $firebase(db);
messages.$add(message);
}
}
}])
.controller('MainController', ["fireBaseConnectionService", "$scope", function (fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
$scope.messages = fireBaseConnectionService.getMessages();
}])
.controller('AdminController', ["fireBaseConnectionService", "$scope", function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
fireBaseConnectionService.addMessage({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
}
}])
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});
- JSON作为Angular工厂中的变量
- 将一个 Angular 工厂注入另一个工厂
- Angular 工厂未从 Soundcloud (SC.get) 请求返回数据
- 如何使用getter和setter方法创建一个Angular工厂而不遇到竞争条件
- Angular工厂和过滤器$http
- 如何在Angular工厂中保留Scope上的数据
- Angular工厂函数需要返回一些东西吗
- 从服务器获取Angular工厂中新建资源的ID
- Angular:工厂模型中的更新不会反映在控制器中
- 从控制器的下拉选项中获取变量,以改变Angular工厂中的另一个选项
- 从控制器向Angular工厂传递参数
- 如何在angular工厂中放置变量?
- Angular工厂成功和错误回调
- 如何使用angular工厂从rest api返回http get请求
- Angular工厂没有'
- 如何正确使用angular工厂
- Angular工厂服务变量创建机制
- 如何在angular工厂和控制器中使用其他js库中的函数
- angular工厂中$http中的$http
- Angular工厂和它的函数相互调用