E
E
Ekaterina2014-11-04 02:41:19
Angular
Ekaterina, 2014-11-04 02:41:19

How to load data with possibly different types into the controller?

Angular used to support the ability to load data directly from a Promise. For logical reasons (not obvious assignment), this feature was removed.
Now you need to write like this

getdata(1).then(function(data)
{
    $scope.data = data;
});

But, now it is extremely important for me not to exit the stream sometimes, so getdata can return an array directly without a Promise, or it can return a Promise.
To do this, I use a helper function
Simplified like this:
Интерфейс
loadData($scope, name, getter, params);

//и вызов
loadData($scope, 'data',getdata, [1]);

It checks whether the function has returned a Promise or data and accordingly assigns the value to $scope immediately or after then.
Attention, question! Who has any ideas in this direction, maybe there are more beautiful solutions?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Wolf, 2014-11-04
@mannaro

Why is this option bad?

S
Sergey, 2014-11-04
Protko @Fesor

$q.when

$q.when(loadData()).then(function (result) {
    $scope.data = result;
});

But just keep in mind that the callbacks in then are not executed synchronously, but as it happens in the event loop. That is, you may have a couple of milliseconds to pass between the call to loadData and the callback in then. If this is critical for you, you can use your solution.

_
_ _, 2014-11-04
@AMar4enko

So you contradict yourself.

But, now it is extremely important for me not to go out of the flow sometimes
and at the same time admit that a promise can return.
You probably have a misunderstanding somewhere. Please describe the situation in more detail.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question