0

I am getting data from firebase firestone, data is successfully retrieved and printed in the console. but I am unable to save the data into a global variable. this error located exactly on line 37.

I want to save the data to that variable to load the data in the ui.

24 thisaddress = {};
25  ngOnInit() {
26    this.data = new AddressserviceService();
27    this.sub = this.route.params.subscribe(params => {
28      this.id = params['id'];
29   });
30   
31   this.newvisitordb = AddressserviceService.getdb();
32   var docRef = this.newvisitordb.collection("addresses").doc(this.id);
33   docRef.get().then(function(doc) {
34        if (doc.exists) {
35          console.log("Document data:", doc.data());
36          //**this line is not working**
37          this.thisaddress= doc.data();
38        } 
39    }).catch(function(error) {
40        console.log("Error getting document:", error);
41    });

Error on line 37

the error is

>     Error getting document: TypeError: Cannot set property 'thisaddress' of undefined
>         at eval (newvisitor.component.ts:45)
>         at ZoneDelegate.invoke (zone.js:388)
>         at Object.onInvoke (core.js:4733)
>         at ZoneDelegate.invoke (zone.js:387)
>         at Zone.run (zone.js:138)
>         at eval (zone.js:858)
>         at ZoneDelegate.invokeTask (zone.js:421)
>         at Object.onInvokeTask (core.js:4724)
>         at ZoneDelegate.invokeTask (zone.js:420)
>         at Zone.runTask (zone.js:188)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
vishnu vigneshwar
  • 109
  • 1
  • 1
  • 7
  • This question has already been answered [here](https://stackoverflow.com/questions/45609186/angular-4-typescript-callaback-with-this-in-block/45609369#45609369). – JeanPaul A. Jan 26 '18 at 12:42

1 Answers1

2

Try change

docRef.get().then(function(doc) {

to

docRef.get().then((doc) => {
Kim
  • 1,158
  • 8
  • 18