Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this function. Currently, I am looping through my user collection and displaying the data on the console using the code snippet provided below:
page1.ts:81 key -KFoJ-oF-ll04zmxJZiL
page1.ts:88 data Object {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f28196918196b2959f939b9edc919d9f">[email protected]</a>", username: "cesscd"}
page1.ts:89 user UserAllowed {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cab9aea9b9ae8aada7aba3a6e4a9a5a7">[email protected]</a>", username: "cesscd"}
However, when trying to add a new user to the allowed user array, I encounter the following error;
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'alloweduser' of undefined
at http://localhost:8100/build/js/app.bundle.js:98:21
at https://cdn.firebase.com/js/client/2.4.1/firebase.js:200:356
at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:275)
at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
at Kc.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:35:268)
at Ec.h.ka (https://cdn.firebase.com/js/client/2.4.1/firebase.js:32:465)
at fe.h.R (https://cdn.firebase.com/js/client/2.4.1/firebase.js:83:379)
at W.forEach (https://cdn.firebase.com/js/client/2.4.1/firebase.js:200:326)
at http://localhost:8100/build/js/app.bundle.js:88:22
Code base
export class Page1 {
reponse:string;
firebaseUrl:string;
userRef:Firebase;
alloweduser: UserAllowed[];
constructor() {
this.firebaseUrl = "https://fghghgf-hefghgfhat-gh.firebaseio.com/web/data/";
this.userRef = new Firebase(this.firebaseUrl).child("users");
}
ngOnInit(){
this.alloweduser=[];
this.userRef.once("value", function(snapshot) {
// The callback function will get called twice, once for "fred" and once for "barney"
snapshot.forEach(function(childSnapshot) {
// key will be "fred" the first time and "barney" the second time
var key = childSnapshot.key();
console.log("key",key);
// childData will be the actual contents of the child
var childData = childSnapshot.val();
var user = new UserAllowed("","");
var user = new UserAllowed(childData.username,childData.email);
console.log("data",childData);
console.log("user",user);
//Why this.alloweduser get undefined inside this function?
this.alloweduser.push(user);
});
});
}
}
// TypeScript
class UserAllowed {
email: string;
username: string;
constructor(username:string, email: string) {
this.email = email;
this.username = username;
}
}