Marco Grieco
Marco Grieco

Reputation: 229

Null object in promise Angular2

i'm developing an Ionic2 app and I'm using promises. In a Typescript class I have created this method

tapOnRegistrati() {
this.authService.userRegistration(this.email,this.password).then(function(user){

  this.user = this.af.database.object('/users/' + user.uid);
  this.user.set({ name: this.name, lastname: this.lastname});


}).catch(function(error: any) {

});

}

but when the then block is executed this's reference is null, so I can't use any object/attribute of my typescript class. Why?

Upvotes: 2

Views: 363

Answers (1)

eko
eko

Reputation: 40677

Because if you use your callback function like

.then(function(user){
  this.user = this.af.database.object('/users/' + user.uid);
  this.user.set({ name: this.name, lastname: this.lastname});    
})

this will refer to the function object inside the callback. If you want to refer to the page, use:

then((user)=>{
  this.user = this.af.database.object('/users/' + user.uid);
  this.user.set({ name: this.name, lastname: this.lastname});

})

Upvotes: 1

Related Questions