【问题标题】:Angular passing data from factory to controller从工厂到控制器的角度传递数据
【发布时间】:2015-01-22 15:03:35
【问题描述】:

我正在尝试存储一个授权用户 id 变量,我可以将其传递给控制器​​。我知道我尝试从工厂对象的闭包内部传递数据的方式存在问题,但我一直不知道如何解决它。

这是我的工厂:

myApp.factory('Authentication', function($firebase, 
  $firebaseAuth, FIREBASE_URL, $location) {

  var ref = new Firebase(FIREBASE_URL);
  var simpleLogin = $firebaseAuth(ref);

  var authorized;

  var myObject = {
    login : function() {
    return simpleLogin.$authAnonymously().then(function(authData) {
    authorized = authData.uid;
  console.log("Logged in as:", authData.uid);
}).catch(function(error) {
  console.error("Authentication failed:", error);
});
    },
    auth : authorized
  } //myObject

  return myObject;
});

这是我的控制器:

myApp.controller('MeetingsController', 


function($scope, $firebase, Authentication) {

  var ref = new Firebase('http://i2b2icons.firebaseio.com/');
  var meetings = $firebase(ref);

  $scope.authid = Authentication.auth;

  $scope.meetings = meetings.$asObject();
//  $scope.id = = Authentication.login.id;  
  $scope.addMeeting=function() {
    meetings.$push({
      name: $scope.meetingname,
      date: Firebase.ServerValue.TIMESTAMP
    }).then(function() {
      $scope.meetingname = '';
    });
  } //addmeeting

  $scope.deleteMeeting=function(key) {
    meetings.$remove(key);
  } //deletemeeting

}); //MeetingsController

我真的只是想从 myObject 的登录函数中获取 $scope.authid 变量来获取 auauthorized 的值。

应该已经通过这个控制器登录调用了登录方法:

myApp.controller('RegistrationController', 


function($scope, $firebaseAuth, $location, Authentication) {


  $scope.login = function() {
    Authentication.login();
  } //login


}); //RegistrationController

【问题讨论】:

  • Authentication.auth` 仅设置在 Authentication.login 内部,这是您没有调用的函数。

标签: angularjs firebase


【解决方案1】:

您只是在工厂中设置局部变量 authorized,它与您尝试在控制器中访问的 Authentication.auth 无关(当然,除非您在创建因子时为其设置了值,并且反正不是本意)。而是在您的工厂中返回一个预定义的对象并从中返回该对象。在对象引用上设置属性。

myApp.factory('Authentication', function($firebase, 
      $firebaseAuth, FIREBASE_URL, $location) {

    var ref = new Firebase(FIREBASE_URL);
    var simpleLogin = $firebaseAuth(ref);
    //Predefine the factory
    var factory = {
       login: login,
       authorized: null
    };

    function login() {
       return simpleLogin.$authAnonymously().then(function(authData) {
          factory.authorized = authData.uid; //Set the property here
      }).catch(function(error) {});
    } 
   //return it
   return factory;
});

如果您拥有工厂的引用,并且对其属性的更新将反映(假设您调用填充数据的方法)在您的控制器中。另一种方法是在您的工厂中使用 getter 函数来返回 auth 对象,或者您也可以缓存 login 函数返回的承诺,并在发生注销用户的事件时将其返回并使其无效。

【讨论】:

  • 谢谢!这很有意义,并清除了很多事情。
【解决方案2】:

正如其他人已经指出的那样,您只更新变量authorized,而不是属性auth。一个相当简单的解决方案是将 auth 更改为一个 getter,它总是返回当前值:

var myObject = {
  login : function() {
    ...
  },
  get auth() {
    return authorized;
  }

您不必更改任何其他代码。

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 2018-03-07
    • 1970-01-01
    • 2013-08-16
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2015-09-16
    相关资源
    最近更新 更多