ruby on rails - Unable to get $rootscope object on pageload in angularjs -


i using ng-token-auth , devise token-auth.

when user gets logged in stores user.id in $rootscope

this controller

app.controller('myctrl', function($rootscope,myfactory){      console.log($rootscope);      console.log($rootscope.user.id); }) 

the output first is:

object {$id: 1, $$childtail: object, $$childhead: object, $$prevsibling: null, $$nextsibling: null…}
output 2nd is:
undefined

but when expand first output contains user.id
user: object
configname: "default"
email: "abc@gmail.com"
id: 3
provider: "email"
signedin: true
status: null
uid: "17d851ed-4"
proto: object

the reason might you're trying access property, not yet assigned (maybe promise being resolved or something?).

to make sure, add debugger statement in controller , see if actual user property @ given moment.


to defer action use user.id, try following:

app.controller( 'myctrl', function( $rootscope, myfactory ) {   var unwatch = $rootscope.$watch( 'user.id', function ( id ) {     if ( angular.isdefined( id ) {       // use id, seems defined       console.log( id );        // remove watch, because there's no more use       unwatch();     }   }); }); 

to create better, reusable functionality, can create small service return promise, so:

app.service( 'getuserid', function( $rootscope, $q ) {   var deferred = $q.defer();    var unwatch = $rootscope.$watch( 'user.id', function ( id ) {     if ( angular.isdefined( id ) {       // resolve promise, seems defined       deferred.resolve( id );        // remove watch, because there's no more use       unwatch();     }   });    return function () {     return deferred.promise;   } });  // let's use it: app.controller( 'myctrl', function( getuserid ) {   // value returned service promise resolved user.id   getuserid().then( function ( id ) {     // use id   }); }); 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -