1

Let's say you define a variable like below (snackbar). It's accessible by the rest of the Angular class with this, but not in the callbacks of promises. I'm using AngularFire 5.

export class SomeComponent implements OnInit {
    constructor(private snackbar: MatSnackBar, private afs: AngularFirestore) {}    

    //Promise function
    this.afs.doc(path).set({
        ...some code
    }).then(function(docRef){
        this.snackbar.open('Snackbar message', 'OK');  //Sanckbar unreachable
    });

    //Regular function
    this.snackbar.open('Snackbar message', 'OK');  //Sanckbar works fine
}

How would someone reach those variables from inside the then? Or is it just not possible?

FiringBlanks
  • 1,998
  • 4
  • 32
  • 48

1 Answers1

2

That is a JavaScript "feature"

Use

 }).then((docRef) =>{

instead of

 }).then(function(docRef){

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567