-1

I have this Angular code, which is giving me an error on the line with: vm.lps.sort()

(() => {
  angular
    .module('app')
    .controller('appController', appController)

  appController.$inject = ['$http', '$scope', '$rootScope'];

  function appController ($http,$scope, $rootScope) {
    let vm = this;
    $http.get('/user/username/').then(function(response){
      vm.names = response.data.lps;
    })

    //Sort the array 
    vm.names.sort();
..................
..................
}
})()

and the error is:

Cannot read property 'sort' of undefined
    at new appController

Why is it happening ?

Kemal P.
  • 143
  • 1
  • 7

2 Answers2

-1

Http request returns a promise that the data will be avaiable in future time, you can't read property sort of undefined cause tha data is still not avaiabile. Try with this

$http.get('/user/username/').then(function(response){
      vm.names = response.data.lps;
      vm.names.sort();
    }).catch(function error(){
     //define error behaviour here
   });
shall
  • 154
  • 9
-1

At the point that vm.names.sort() is called, vm.names doesn't point to an array, it's still undefined.

You'd probably want to modify your controller like this:

$http.get('/user/username/').then((response) => {
    vm.names = response.data.lps.sort();
});
RogerH
  • 21
  • 6