angularjs - Angular method returns as undefined rather than JSON object -
i have getuser method within authentication provider (working in ionic 2):
getuser(uid: string): { var toreturn; firebase.database().ref('/userprofile').orderbykey().equalto(uid).once("value", function(snapshot){ toreturn = snapshot.val(); console.log("getuser = " + json.stringify(toreturn)); }); return toreturn; }
it retrieves user object firebase. gets output correctly console.log providing exists , saved in toreturn variable.
below itemdetailpage class when log value of same method, returns undefined.
import { component } '@angular/core'; import { navparams} 'ionic-angular'; import { auth } '../../providers/auth/auth'; @component({ templateurl: 'build/pages/item-detail/item-detail.html', providers: [auth] }) export class itemdetailpage { private title; private description; private author; constructor(private navparams: navparams, private _auth: auth) { this.title = this.navparams.get('item').title; this.description = this.navparams.get('item').description; this.author = _auth.getuser(this.navparams.get('item').author); console.log("item-detail.ts = " + json.stringify(this.author)); //_auth.getuser('123'); } }
i'm new angular , trying learn go along, quite simple i'm missing out. however, why json object not returned/passed back? need utilise values queried database.
thanks
what missing firebase method running assincronously. so, return promise instead of value. that's why returned value callback.
what should is: return firebase promise in service (or new 1 in case want data before returning controller). want create callback function controller.
return firebase.database().ref('/userprofile').orderbykey().equalto(uid).once("value", function(snapshot){}); // controller _auth.getuser(this.navparams.get('item')).then(function(snapshot){ ... });
you should take how promises work in plain javascript:
http://andyshora.com/promises-angularjs-explained-as-cartoon.html
and how used in ng2 style
http://coenraets.org/blog/2016/02/angular2-ionic2-data-services-promises-observables/
Comments
Post a Comment