简体   繁体   English

如何使用Firebase将用户数据从Factory返回到控制器

[英]How to return user data from Factory into a controller using Firebase

I have a factory which checks the authData of a user, using firebase. 我有一个工厂,使用firebase检查用户的authData。 I wish to access the users details such as name, email etc, but I can't figure out how to get the snapshot data into an object which I can use. 我希望访问用户的详细信息,例如姓名,电子邮件等,但是我不知道如何将快照数据转换为可以使用的对象。 I'm new to Javascript. 我是Java的新手。

this is my factory: 这是我的工厂:

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;
});

2nd Attempt: 第二次尝试:

This time i am able to get the users details, but it won't save into the variable service and is returning to the controller as null. 这次,我可以获取用户详细信息,但是它不会保存到变量服务中,并以null返回给控制器。 Here is my code: 这是我的代码:

   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;

You need to inject your service inside something (controller, service, filter or directive) and from the controller, call the service function. 您需要将服务注入到某个东西(控制器,服务,过滤器或指令)中,然后从控制器中调用服务函数。

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

Now you can call the function from your controller scope. 现在,您可以从控制器范围调用该函数。

userService.authDataCallback()

You assign snapshot.val() to a local variable data . 您将snapshot.val()分配给局部变量data data is destroyed as soon as the function ends. 函数结束后, data将立即销毁。

You need to assign it to the "outer" variable authData , which you can't because you have a function parameter with the same name. 您需要将其分配给“外部”变量authData ,因为具有相同名称的函数参数,所以您不能这样做。

Try it like this: 像这样尝试:

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
    };
});

Also you should read up on the return types of service/factory in the docs. 另外,您应该在文档中阅读服务/工厂的退货类型。 What the returned object of a factory does, is basically expose private variables/functions for other modules to access. 工厂返回的对象所做的基本上是公开私有变量/函数供其他模块访问。

Assuming the snapshot is correct, the val() method turns it into an object. 假设快照是正确的,则val()方法将其变成一个对象。 Meaning data now contains the values you need. 含义数据现在包含您需要的值。 For example data.name. 例如data.name。

The service should expose a function for this 服务应为此提供一个功能

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;
}

Something like this 像这样

Cheers 干杯

I suppose there is in var data an object. 我想在var数据中有一个对象。 You can access fields easily with dot .field . 您可以使用dot .field轻松访问字段。 For example: 例如:

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

Depending on the data in a DataSnapshot, the val() method may return a primitive (string, number, or boolean), an array, or an object. 取决于DataSnapshot中的数据,val()方法可能返回原语(字符串,数字或布尔值),数组或对象。 It may also return null, indicating that the snapshot is empty and contains no data. 它还可能返回null,表示快照为空并且不包含任何数据。

Taken from: https://www.firebase.com/docs/web/api/datasnapshot/val.html 摘自: https : //www.firebase.com/docs/web/api/datasnapshot/val.html

I hope it helps. 希望对您有所帮助。

-EDIT- Use this format to get data in the controller: -编辑-使用以下格式来获取控制器中的数据:

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;
    });
  }
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM