M
M
mrdunner2015-11-07 17:15:49
Angular
mrdunner, 2015-11-07 17:15:49

AngularJS. Is he me or am I him?

Hello.
The problem is this: I
'm using AngularJS. Set up, like, everything is as it should be. More precisely, I set everything up according to the instructions.
And I want to drive all the data into a separate subobject of the $rootScope object in the 'run' function.
It seems to have driven it, but does not want to from under the controller.
Piece of code:

app.run(function($rootScope,$http) {
    $http.get('/webapi/amilogged').success(function(data) {if (data!=='1'){window.location = '/';}else{
    $http.get('/webapi/whoiam').success(function(data) {
      var un = angular.fromJson(data);
      $rootScope.profile = data;
    });
  }});
})
app.controller('peopleCtrl', function($scope, $rootScope) {
  console.log($rootScope.profile);
})

When accessing peopleCtrl , undefined is printed to the console.
What needs to be done to make the variables visible both in run and in controllers?
The request in advance not to kick for govnokod.
Happy Sunday everyone =)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yaroslav Lyzlov, 2015-11-07
@mrdunner

First: format the code the way you want it.
Second: You don't understand the core principle of JavaScript - asynchrony. So it's too early for you to use angular.
In the run function, you are making a request to the server, it is asynchronous, and when the controller is initialized, $rootScope.profile does not exist.
To make it all work... I doubt that you will understand, but still:
If you want to get data in the controller before it is loaded, then routing has a resolve property. Read about it.
AngularJS preload, how to file it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question