简体   繁体   中英

function to return string angularjs firebase

I started angularjs 2 days ago (...) I'm currently asking myself how to create a function that fetches my firebase data and depending on the child, it returns a string.

Seems pretty simple when I say it, but harder to do...

I could fetch the data one by one but the problem is that there are a total of 84 childs!!

My Context The website retrieves from firebase if a person is working night, day or evening, for the 7 days of the week, for 4 weeks in a month (3x7x4 = 84). An example of one of my child is: Saturday1Night: true where "1" means week 1.

What I tried

function getOneDay(currentUserId, key, query, text){
  firebase.database().ref().child('Users').child(currentUserId).child(key).once('value').then(function(snapshot) {
    /* query is "Saturday1Night" */
    if(datasnapshot.$value === null && datasnapshot.id === null) {
      /* not working */
      text = 'X';
    }else{
      /* value is "true", person is working */
      text = query;
    }

  })
  return text;
}

Now my real question is, how can I, like in java for example, create a function that returns a string? How can I display it in my $scope?

html

<h1>{{s1n}}</h1>

angularjs

$scope.s1n = text; //??
$scope.s1n = getOneDay(/*uid*/, /*key*/, "Saturday1Night", $scope.s1n) //??

Thank you in advance, have a good night/day!

The Firebase Realtime Database APIs are asynchronous, meaning that once() returns immediately. Some time later, it will invoke your callback when the data becomes available. This means that your getOneDay function also returns immediately with an undefined value, because text doesn't have a value at the time it's evaluated.

You can't really make a function that returns a value from Realtime Database. You need to deal with its asynchronous APIs with the promises or callback they provide.

Read here to learn more about why Firebase APIs are asynchronous.

You can try async-await:

    async function getOneDay(currentUserId, key, query, text){

        var datasnapshot = await firebase.database().ref().child('Users').child(currentUserId).child(key).once('value');

        if(datasnapshot.$value === null && datasnapshot.id === null) {
          /* not working */
          text = 'X';
        }else{
          /* value is "true", person is working */
          text = query;
        }


      return text;
    }
    $scope.s1n = await getOneDay(/*uid*/, /*key*/, "Saturday1Night", $scope.s1n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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