【问题标题】:How to properly setup factory如何正确设置工厂
【发布时间】:2015-04-15 10:25:02
【问题描述】:

我正在尝试将我的 Firebase 身份验证逻辑从控制器转移到工厂,但遇到了基本设置问题。我正在使用 Angularfire 在我的应用中完成身份验证,并遵循文档here

在我的控制器中一切正常,但我不确定如何在工厂中正确设置代码。我当前的代码如下:

angular
  .module('app')
  .factory('authService', authService);

authService.$inject = ['$firebaseAuth'];

var ref = new Firebase('https://[MY-FIREBASE].firebaseio.com');
var auth = $firebaseAuth(ref);

return {
    createUser(email,password): auth.$createUser({
        email: email,
        password: password
    }).then(function(userData) {
        $location.path('/people');
    }).catch(function(error) {
        alert(error);
    }),

    connectFacebook: auth.$authWithOAuthPopup("facebook").then(function(authData) {
        $location.path('/places');
    }).catch(function(error) {
        alert("Authentication failed:", error);
    }),

    removeUser: auth.$removeUser({
        email: vm.email,
        password: vm.password
    }).then(function() {
        alert('User removed');
    }).catch(function(error) {
        alert(error);
    })
}

我的目标是将这个工厂注入我的登录控制器并连接调用适当函数的点击事件,例如authService.createUser($scope.email,$scope.password);

【问题讨论】:

    标签: javascript angularjs firebase factory angularfire


    【解决方案1】:

    这更像是一个使用服务而不是工厂的用例。

    使用函数语法而不是这种对象样式来设置工厂/服务要容易得多。

    angular.module('app', [])
    
    .service('AuthService', function($firebaseAuth) {
      var ref = new Firebase('https://[MY-FIREBASE].firebaseio.com');
      var auth = $firebaseAuth(ref);
    
      this.createUser = function(email, password) {
        // ...
      };
    
      this.connectFacebook = function() {
        // ...
      };
    
      this.removeUser = function(email, password) {
        // ...
      };
    })
    

    服务会公开附加到 this 的任何内容,我们可以将其注入并在应用程序的其他地方使用它。

    .controller('AuthController', function($scope, AuthService) {
      $scope.email = '';
      $scope.password = '';
    
      $scope.register = function() {
        AuthService.createUser($scope.email, $scope.password); 
      };
    })
    

    【讨论】:

    • 谢谢!老实说,在这个解释之前,我还没有完全掌握服务的有用性。许多课程和教程通过掩饰服务并说“在几乎所有情况下工厂将是最佳选择”,从而造成损害。出于这个原因,我一直在寻求让工厂满足我的需求,现在不再这样了!
    • Angular 教程的前景可能会令人困惑。我还没有找到一个我认为在用例之间有非常清晰的区别的方法,但我已经提出了一套我自己的规则,效果很好。
    【解决方案2】:

    这是我工厂的样子:

    angular.module('myApp').factory('RegistrationFactory', ['$http', function($http) {
    
        var urlBase = '/api/';
        var dataFactory = {};
    
        dataFactory.IsRegistered = function () {
            return $http.get(urlBase);
        };
    
        dataFactory.RegisterUser = function (username, password, deviceId) {
            var RegistrationObj = { registration: { DeviceReference: deviceId, Username: username, Password: password, VehicleReg: "" } };
            return $http.post(urlBase + 'RegisterDevice', RegistrationObj);
        };  
        return dataFactory;
    }]);
    

    然后我可以像这样在我的控制器中使用它:

    angular.module('myApp').controller('RegisterCtrl', function ($scope, RegistrationFactory) {
        RegistrationFactory.RegisterUser(username, password, $cordovaDevice.getUUID())
    });
    

    【讨论】:

      【解决方案3】:

      您需要包含一些功能才能使一切正常...

      (function() {
          "use strict";
          angular
            .module('app', []) // dont forget the '[]' here
            .factory('authService', authService);
      
          authService.$inject = ['$firebaseAuth'];
      
          function authService($firebaseAuth) {
            var ref = new Firebase('https://[MY-FIREBASE].firebaseio.com');
            var auth = $firebaseAuth(ref);
      
              return {
                  createUser: function(email,password) {
                    auth.$createUser({
                        email: email,
                        password: password
                    }).then(function(userData) {
                        $location.path('/people');
                    }).catch(function(error) {
                        alert(error);
                    })
                  },
      
                  connectFacebook: auth.$authWithOAuthPopup("facebook").then(function(authData) {
                      $location.path('/places');
                  }).catch(function(error) {
                      alert("Authentication failed:", error);
                  }),
      
                  removeUser: auth.$removeUser({
                      email: vm.email,
                      password: vm.password
                  }).then(function() {
                      alert('User removed');
                  }).catch(function(error) {
                      alert(error);
                  })
              }
          }
      }());
      

      然后我们将它全部包装在一个 IIFE 中并从窗口中删除所有全局变量。

      【讨论】:

        猜你喜欢
        • 2013-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        • 2015-08-02
        • 1970-01-01
        相关资源
        最近更新 更多