A
A
Artur Bekerov2014-11-28 14:15:01
Angular
Artur Bekerov, 2014-11-28 14:15:01

How to make code work for Angular promise?

Have a service

crmServices.factory('Insurances', ['$resource',
    function ($resource) {
        return $resource('api/public/insurances/:id', {}, {
            query: {method: 'GET', isArray: true,  cache: true},
            get: {method: 'GET', isArray: false},
            save: {method: 'POST'},
            update: {method: 'PUT'},
            delete: {method: 'DELETE'}
        });
    }]);

there is a code in the control
$scope.insurances = Insurances.query()
$scope.getLen = function() {
        return = $scope.insurances.length
    }

Until the data arrives from the service, errors are thrown in the console.
TypeError: Cannot read property 'length' of undefined

I imagine that I need to solve with $q and promises but it doesn't work out.
Maybe someone has a ready code?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
_
_ _, 2014-11-28
@AMar4enko

You would write how the insurances in the osprey appear.
It may be enough $scope.insurances = [];, it may be worth moving the data acquisition into the resolve section. Lots of options, all have their pros and cons.

B
Boris Benkovsky, 2014-11-28
@benbor

$scope.getLen = function() {
        $scope.insurances.query().then(function(data) {
                 $scope.length = data.length
       });
}

Insurances is a service, not a ready-made collection (array). It has only those methods that you passed (query, get, save ..... ) Above is pseudocode, I don’t remember exactly, maybe data will contain HttpResponse and not a ready-made array

N
Nikita Gushchin, 2014-11-28
@iNikNik

In your case, it's enough just to check the promise for resolveved:

$scope.getLen = function() {
    if(!$scope.insurances.$resolved)
        return 0;
    return $scope.insurances.length;
}

Otherwise, use promise.then

M
Mikhail Osher, 2014-11-28
@miraage

I strongly recommend using Restangular for such purposes .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question