0

我有一个工厂,它使用 firebase 检查用户的 authData。我希望访问用户的详细信息,例如姓名、电子邮件等,但我不知道如何将快照数据放入我可以使用的对象中。我是 Javascript 的新手。

这是我的工厂:

angular.module('.....')
  .factory('UserDataService', function($q, $firebase, $firebaseAuth, FIREBASE_URL) {
    var authData = {};

    function authDataCallback(authData) {
      if (authData) {
        var ref = new Firebase(FIREBASE_URL + "/userProfiles/" + authData.uid);
        ref.on("value", function(snapshot) {
          var data = snapshot.val();
        });

      } else {
        console.log("User is logged out");
      }
    }

    // Register the callback to be fired every time auth state changes
    var ref = new Firebase(FIREBASE_URL);
    ref.onAuth(authDataCallback);

    return authData;
});

第二次尝试:

这次我能够获取用户详细信息,但它不会保存到变量服务中,而是以空值返回到控制器。这是我的代码:

   var firebaseRef = new Firebase(FIREBASE_URL);
    var authObj = $firebaseAuth(firebaseRef);
    activate();
    var service = {
        userInfo: null
    };


    function activate() {
        // Add listeners for authentication state changes
        authObj.$onAuth(function(authData) {
            if (authData) {
                // Load the userInfo
                loadUserInfo(authData);
            } else {
                // Destroy the userInfo Object if one exists
                if (service.userInfo) {
                    service.userInfo.$destroy();
                    service.userInfo = null;
                }
            }
        });
    }

    function loadUserInfo(authData) {
        var userRef = firebaseRef.child('userProfiles').child(authData.uid);
        var loadedInfo = $firebaseObject(userRef);
        // console.log(loadedInfo);

        loadedInfo.$loaded()
        .then(function() {
            service.userInfo = loadedInfo;
            console.log(service.userInfo.name);
        })
        .catch(function(error) {
            switch (error.code) {
                case 'PERMISSION_DENIED':
                    alert('You don\'t have the permission to see that data.');
                    break;
                default:
                    alert('Couldn\'t load the user info.');
            }
        });
    }
    return service;
4

4 回答 4

1

您需要在某些东西(控制器、服务、过滤器或指令)中注入您的服务,并从控制器调用服务函数。

.controller('myController', ['UserDataService', function($scope) {
    $scope.userService = UserDataService;
}

现在您可以从控制器范围调用该函数。

userService.authDataCallback()
于 2015-10-13T13:17:25.623 回答
1

您将 snapshot.val() 分配给局部变量datadata函数一结束就被销毁。

您需要将其分配给“外部”变量authData,因为您有一个同名的函数参数,所以您不能这样做。

试试这样:

angular.module('.....')
  .factory('UserDataService', function($q, $firebase, $firebaseAuth, FIREBASE_URL) {
    var authData = {};

    function authDataCallback(data) {
      if (data) {
        var ref = new Firebase(FIREBASE_URL + "/userProfiles/" + data.uid);
        ref.on("value", function(snapshot) {
          authData = snapshot.val();
          //[see comment] var authData = snapshot.val();
        });

      } else {
        console.log("User is logged out");
      }
    }

    // Register the callback to be fired every time auth state changes
    var ref = new Firebase(FIREBASE_URL);
    ref.onAuth(authDataCallback);

    return {
        authData: authData
    };
});

您还应该阅读文档中服务/工厂的返回类型。工厂返回的对象所做的基本上是公开私有变量/函数以供其他模块访问。

于 2015-10-13T13:18:59.313 回答
0

我想在var data中有一个对象。您可以使用点.field轻松访问字段。例如:

ref.once("value", function(snapshot) {
   var data = snapshot.val();
   // data is { "name": "Fred", "age": 53 }
   // data.name === "Fred"
   // data.age === 53
});

根据 DataSnapshot 中的数据,val() 方法可能会返回一个基元(字符串、数字或布尔值)、一个数组或一个对象。它也可能返回 null,表示快照为空且不包含数据。

取自: https ://www.firebase.com/docs/web/api/datasnapshot/val.html

我希望它有所帮助。

-EDIT- 使用此格式在控制器中获取数据:

var app = angular.module("sampleApp", ["firebase"]);

app.factory("Auth", ["$firebaseAuth",
  function($firebaseAuth) {
    var ref = new Firebase("https://docs-sandbox.firebaseio.com", "example3");
    return $firebaseAuth(ref);
  }
]);

app.controller("SampleCtrl", ["$scope", "Auth",
  function($scope, Auth) {
    $scope.auth = Auth;

    // any time auth status updates, add the user data to scope
    $scope.auth.$onAuth(function(authData) {
      $scope.authData = authData;
    });
  }
]);
于 2015-10-13T13:20:35.747 回答
0

假设快照是正确的,val() 方法会将其转换为对象。含义数据现在包含您需要的值。例如 data.name。

该服务应该为此公开一个功能

function sendData() {
  var deferred = $q.defer();
  // Register the callback to be fired every time auth state changes
  var ref = new Firebase(FIREBASE_URL);
  ref.onAuth(function(snapshot) {
     deferred.resolve(snapshot.val());
  });

  return deferred.promise;
}

像这样的东西

干杯

于 2015-10-13T13:15:40.273 回答