简体   繁体   中英

Cannot set property of null in angular-2 when using this?

Hi I'm getting an error in

angular2-polyfills.js:143 Uncaught TypeError: Cannot set property 'singlehotel' of null(…)

and a warning from Firebase

FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'singlehotel' of null

When I tried to get the data from Firebase I am getting this error, any one please help to to resolve this.

Thanks in advance!

here is my code

ngAfterContentInit() {

       this.singlehotel = {};
       firebase.database().ref('Rests/').once('value', function(snapshot) {
         console.log('value from db' + JSON.stringify(snapshot.val()));
         var getrest = snapshot.val();
         console.log(JSON.stringify(getrest));

           for (var key in getrest) {

                  if(restemail == getrest[key].email){

          console.log(key + ':' + JSON.stringify(getrest[key]));
                          this.singlehotel = getrest[key]; //getting error here when using this

         }         
            }
         });                
      };

index.html

<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js"></script>
    <script>
      // Initialize Firebase
      // for security reasons i am hiding my keys 
      var config = {
        apiKey: "***",
        authDomain: "***",
        databaseURL: "***",
        storageBucket: "**",
        messagingSenderId: "**"
      };
      firebase.initializeApp(config);
    </script>
       <body>
      <my-app>Loading...</my-app>
    </body>

view

<div class="container" style="background-color: #f2f2f2;">
    <h1><b>Hotel Name :{{singlehotel.displayName}}</b></h1>
</div>

both belongs to same componet.when the view gets loaded the ngAfterContentInit() function willi be called every time , thats how the function triggers but i am not able to store in scope i mean this.please help me

this doesn't point to the current class instance if you use function() {... } . Use arrow functions instead

firebase.database().ref('Rests/').once('value', (snapshot) => {

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

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