如何正确使用angular工厂

How to use an angular factory correctly?

本文关键字:angular 工厂 何正确      更新时间:2023-09-26

我读了很多关于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);
});