Simple data binding question?

Just starting to learn Angular2/Ionic2 (from Ionic 1)

Scenario: I have a service which is successfully authenticating users from a Firebase database. My goal is to capture the logged in user’s name for use in other components. In the component I can successfully access the user name and display it on the console, but I cannot get the name to bind via string interpolation. It seems like it should be easy - but I am missing something.

In the service (AuthData):

getUserName() {
var userId = firebase.auth().currentUser.uid;
// console.log('UserId = ', userId);

this.userRef = firebase.database().ref('/userProfile/' + userId + '/name');
return this.userRef;

}

In the component:

getCurrentUser() {
var userName = this.authData.getUserName();

userName.on('value', function (snapshot) {
  var getName = snapshot.val();
  console.log('User email is: ', getName);

});
this.getName = getName; //<-- error here
}

Error is: Exception was thrown by user callback. TypeError: Cannot set property ‘getName’ of null

If I use this.getName in the snapshot callback I get an error. How do i pass the snapshot.val() to a variable or property than can data bind to {{ getName }} in the html?

Many thanks.

I would recommend looking at angularfire2. It will probably seem overwhelming at first, but you’ll be led in the right direction. You are trying to make asynchronous code work in synchronous fashion, which just won’t work.

Thanks. I am using angularfire2 in other parts of the app. Just easier to use firebase.database().ref here.

To see if it made any difference I move the code directly to the Page component. The issue is still the same:

return firebase.database().ref('/userProfile/' + userId).once('value').then(function (snapshot) {
  var username = snapshot.val().name;
  console.log('Once username: ', username);  // <-- this returns the correct data
  this.getName = username;  // <-- this returns an error (trying to set the data binding value)
});

Error is:

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property ‘getName’ of null

Try to replace in your code:

function (snapshot)

with

snapshot =>

so that this.getName refers to your member variable.

That worked. Many thanks.

With the original

function (snapshot)

the solution was to use

self = this

then

self.getName

Your solution is much better, particularly as I want to be using fat arrows.