A
A
Alex2016-05-15 20:23:21
Angular
Alex, 2016-05-15 20:23:21

How to get value asynchronously in Angular?

Hello. I'm trying to make a browser extension in angular. But there is a problem with getting data asynchronously.
The user ID is stored in the browser's memory. And this meaning is used everywhere.
Here is a simple example:

angular.module('PopupApp', [])

  .config(['$provide', function ($provide) {
    console.log('.config');
    $provide.value('ID',null);

    chrome.storage.local.get('ID', function (stg) {
      console.log('.config.chrome.storage.local.get');
      console.log('.config.chrome.storage.local.get, ID:' + stg.ID);
      $provide.value('ID',stg.ID);
    });
  }])

  .run(['ID', function (ID) {
    console.log('.run');
    console.log('.run, ID:' + ID);
  }])

  .controller('MyCtrl', ['$scope', 'ID', function ($scope, ID) {
    console.log('.controller');
    console.log('.controller, ID:' + ID);
    $scope.ID = ID;
  }]);

The following is output to the console:
.config
.run
.run, ID:null
.controller
.controller, ID:null
.config.chrome.storage.local.get
.config.chrome.storage.local.get, ID:123

As you can see, in sections runand controllerthe variable is IDempty, because it has not yet been set to a value.
As a solution, use callback functions everywhere that work after receiving the ID. But I thought maybe there is a better solution? Maybe somehow you can pause the work of Angular (So that the section starts configand all the others start only after the data is received)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kumanin, 2016-05-16
@jackkum

Use Promises

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question